我有一个绘制我的位图的表面视图类,我在从屏幕中心底部启动对象到用户点击屏幕的位置时遇到了一些麻烦,下面是一段代码片段 onTouch方法获取用户触摸屏幕的坐标,然后run方法绘制位图。岩石位图是我需要从屏幕底部移动到触摸的位置。
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
sX = event.getX();
sY = event.getY();
fX = fY = dX = dY = sclX = sclY = aniX = aniY = 0;
break;
case MotionEvent.ACTION_UP:
fX = event.getX();
fY = event.getY();
dX = fX - sX;
dY = fY - sY;
sclX = dX / 30;
sclY = dY / 30;
break;
}
return true;
}
//the code that draws and updates the bitmaps on screen
public void run() {
while (running) {
if (!sh.getSurface().isValid())
continue;
canvas = sh.lockCanvas();
canvas.drawRGB(02, 02, 150);
if (x != 0 && y != 0)
canvas.drawBitmap(cross, x - (cross.getWidth() / 2), y- (cross.getHeight() / 2), null);
canvas.drawBitmap(sling,(canvas.getWidth() / 2) - (sling.getHeight() / 2),canvas.getHeight() - sling.getHeight(), null);
if (fX != 0 && fY != 0) {
canvas.drawBitmap(rock, (canvas.getWidth()/2) - aniX,(canvas.getHeight()- sling.getHeight()) - aniY,null);
}
aniX = aniX + sclX;
aniY = aniY + sclY;
sh.unlockCanvasAndPost(canvas);
}
}
答案 0 :(得分:2)
您遗失了onTouch()
中的一些重要内容。
public boolean onTouch(View arg0, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
sX = event.getX();
sY = event.getY();
fX = fY = dX = dY = sclX = sclY = aniX = aniY = 0;
break;
case MotionEvent.ACTION_UP:
fX = event.getX();
fY = event.getY();
dX = fX - sX;
dY = fY - sY;
sclX = dX / 30;
sclY = dY / 30;
break;
}
return true;
}
此代码存在逻辑问题。考虑一下在100/100时点击,sX
和sY
在小写情况下设置为100。在完整的情况下,您可以获得fX
和fY
中的向上坐标,也就是100。这导致dX = fX - sX
=> dX = 100 - 100
。因此,您的sclX
也将是0
。这意味着根本没有动画。
您应该使用屏幕中间作为计算的基础。来源是屏幕中心,目的地是您的触摸。