我在屏幕上有一个球。我想当我实施action_down时,球会移动到这个位置。这是我的代码:
public boolean onTouchEvent(MotionEvent event){
if(event.getAction()==MotionEvent.ACTION_DOWN){
x1 = (int) event.getX();
y1 = (int) event.getY();
float dx = x1-x;
float dy = y1-y;
float d = (float)Math.sqrt(dx*dx+dy*dy);
vx = dx*4/d;
vy = dy*4/d;
}
}
和onDraw:
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Matrix matrix = new Matrix();
matrix2.postTranslate(x - bitmap.getWidth()/2, y - bitmap.getHeight()/2);
x = x+vx ;
y = y+vy ;
canvas.drawBitmap(bitmap, matrix, null);
}
什么时候,球会移动到位置action_down。但是为什么球在位置action_down,它不会停止?
请帮帮我? 谢谢?
答案 0 :(得分:0)
将vx,vy的类型更改为int
vx = (int)dx*4/d;
vy = (int)dy*4/d;
然后使用此
if(Math.abs(x - x1) <= Math.abs(vx)
&& Math.abs(y - y1) <= Math.abs(vy)){
vx = 0;
vy = 0;
x = x1;
y = y1;
}