我正在嘗試拖動併發射一個像憤怒的小鳥一樣的彈丸。拖動部分工作正常,但是當我釋放觸摸(例如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);
}
}
任何幫助表示讚賞。謝謝。
您應該發佈帶有例外的LogCat輸出。 – azertiti 2012-04-22 17:08:01
什麼是xMax和yMax?你有沒有在調試器中完成這一步? – derekerdmann 2012-04-22 17:14:31