android - 如何在 "X"和 "Y"方向移动对象

标签 android math canvas geometry

我在 android studio 上工作,我想创建抛出一个对象的效果,在本例中是在 Canvas 上绘制的一个圆圈。但我有问题。有人可以指导我吗?

我在用户触摸的地方取“X”和“Y”值,但我怎样才能让圆圈朝那个方向移动?

谢谢

游戏类:

public class Game extends SurfaceView implements View.OnTouchListener  {

Paint paint;
int x, y, radius = 100, speedX = 5, speedY = 5, touchY, touchX;
boolean move = false;
boolean one_time = true;

public Game(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setOnTouchListener(this);
    setFocusable(true);

    paint = new Paint();
}


public void onDraw(Canvas canvas){
    paint.setColor(Color.WHITE);
    canvas.drawRect(0,0,canvas.getWidth(),canvas.getHeight(),paint);

    if (one_time == true){
        x = canvas.getWidth()/2;
        y = canvas.getHeight()/2;
        one_time = false;
    }

    paint.setColor(Color.BLACK);
    canvas.drawCircle(x, y, radius, paint);

    if (move == true){

        if (x >= canvas.getWidth() - radius) {
            speedX = -5;
        }

        if (x <= radius) {
            speedX = 5;
        }

        if (y >= canvas.getHeight() - radius) {
            speedY = -5;
        }

        if (y <= radius) {
            speedY = 5;
        }

        x = x + speedX;
        y = y + speedY;
    }

    invalidate();
}

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    switch (motionEvent.getAction()) {
        case (MotionEvent.ACTION_DOWN):

            touchX = (int) motionEvent.getX();
            touchY = (int) motionEvent.getY();

            move = true;

            return true;
        default:
            return super.onTouchEvent(motionEvent);
    }
}

enter image description here

最佳答案

需要在某处设置一个 x+=speedXy+=speedY 以便 x 或 y 值发生变化导致球移动。如果你想在那里实现一些物理学,你将需要一些数学。

关于android - 如何在 "X"和 "Y"方向移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755445/

相关文章:

math - 生成数学方程图像文件的在线工具

java - 尝试将 GSON 与自己的类一起使用时出错

在 Eclipse 中再次安装新软件后 android sdk 损坏

java - Android ffmpeg concat 两个视频声音错误

android - 如何在 Android webview 中播放全屏 youtube 视频?

math - 查找迭代次数,直到某个值达到极限

python - 如何打印数学符号

javascript - AngularJS 在指令模板中使用 Canvas

javascript - 当源是 base64 websocket 数据时,图像 onload 不会触发 javascript

javascript - 究竟如何进行这个循环的进步呢? (兼容Internet Explorer 9,时间准确)