0

我正在尝试拖动并发射弹丸,例如愤怒的小鸟。拖动部分工作正常,但是当我释放触摸(即 ACTION_UP)时,有时球会立即在边界处结束,而其他时候,它会因 StackOverflowError 而崩溃。我应该怎么做才能避免错误并使运动平稳?这是我的代码:

public class BallView extends View{

static Log log;
Bitmap ball;
float xStart;
float yStart;
float xCurrent;
float yCurrent;
int xMax;
int yMax;
float xVector;
float yVector;

public BallView(Context context){
    super(context);
    this.setFocusable(true);
    ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
    xStart = 125;
    yStart = 275;
    xCurrent = xStart;
    yCurrent = yStart;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    xMax = MeasureSpec.getSize(widthMeasureSpec);
    yMax = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(xMax, yMax);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(ball, xCurrent, yCurrent, null);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int eventaction = event.getAction();
    int X = (int)event.getX(); 
    int Y = (int)event.getY(); 

    switch (eventaction ) {
    case MotionEvent.ACTION_DOWN:
        break;
    case MotionEvent.ACTION_MOVE:
        xCurrent = X-30;
        yCurrent = Y-30;
        break; 

    case MotionEvent.ACTION_UP:
        Log.d("actionup", "done");
        xCurrent = X-30;
        yCurrent = Y-30;
        xVector = xStart-xCurrent;
        yVector = yStart-yCurrent;
        break;
    } 
    invalidate();
    if (eventaction == MotionEvent.ACTION_UP){
        launch(xVector, yVector);
    }
    return true; 
}

private void launch(float xVector, float yVector) {
    xCurrent = xCurrent + xVector;
    yCurrent = yCurrent + yVector;
    if (xCurrent < 0 || xCurrent > xMax || yCurrent < 0 || yCurrent >yMax){
        return;
    }
    invalidate();
    launch(xVector, yVector);
}
}

任何帮助表示赞赏。谢谢你。

4

2 回答 2

0

嗯,没有来自错误跟踪的特定信息:StackOverFlow 错误通常与失控的递归函数一起发生。对你来说,launch()如果 xCurrent = 0、xMax = 1000000 和 xVector = .001,你可能会创建一个 stackoverflow。我会从这里开始调试。

此外,您似乎在同一范围内声明了具有相同名称的变量(即 xVector 和 yVector 作为类成员变量,并且它们也在 中声明launch(float xVector, float yVector))。这可能会使您或其他任何人感到困惑。尝试使用不同的变量名称和常规命名方案。

最后,一个有用的运算符是+=,它需要:

xCurrent = xCurrent + xVector;

并将其缩短为:

xCurrent += xVector;

这可以为您节省一些不必要的打字。祝你好运!

于 2012-04-22T17:17:42.890 回答
0

似乎您的launch()方法是一个糟糕的递归调用。看到这个答案

private void launch(float xVector, float yVector) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (!(xCurrent + xVector < 0 || xCurrent + xVector > xMax || 
                    yCurrent + yVector < 0 || yCurrent + yVector > yMax)){

                xCurrent = xCurrent + xVector;
                yCurrent = yCurrent + yVector;
                try{
                    Thread.sleep(200);
                }catch(Exception e){
                }
                postInvalidate();
            }
        }
    }).start;
}
于 2012-04-22T17:44:54.760 回答