我正在尝试拖动并发射弹丸,例如愤怒的小鸟。拖动部分工作正常,但是当我释放触摸(即 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);
}
}
任何帮助表示赞赏。谢谢你。