1

我有一个绘制位图的表面视图类,并且在将对象从屏幕的中心底部启动到用户单击屏幕的位置时遇到了一些麻烦,这是下面的代码片段 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);
        }

    }
4

1 回答 1

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,sXsY在向下的情况下设置为 100。在向上的情况下,您在fX和中获得向上坐标fY,也将是 100。这导致dX = fX - sX=> dX = 100 - 100。所以你的sclX意志0也是。这意味着根本没有动画。

您应该使用屏幕中间作为计算的基础。源是屏幕中心,目标是您的触摸。

于 2012-10-28T12:28:13.517 回答