我在 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);
}
}
最佳答案
需要在某处设置一个 x+=speedX
或 y+=speedY
以便 x 或 y 值发生变化导致球移动。如果你想在那里实现一些物理学,你将需要一些数学。
关于android - 如何在 "X"和 "Y"方向移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755445/