我有一个位图,我使用触摸事件和屏幕中间的矩形移动。有人能告诉我为什么位图和矩形不会发生碰撞吗?我对碰撞问题很新。
感谢。
代码:
public class Juego extends View implements View.OnTouchListener{
Bitmap super_esfera;
int esferaX = 0;
int esferaY = 0;
int left, top, right, bottom;
public Juego(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnTouchListener(this);
setFocusable(true);
super_esfera = BitmapFactory.decodeResource(getResources(), R.drawable.super_esfera);
}
public void onDraw(Canvas canvas){
Paint paint = new Paint();
Bitmap indexcanvas = Bitmap.createScaledBitmap(super_esfera, 200, 200, true);
//Esta es la posicion
canvas.drawBitmap(indexcanvas, esferaX, esferaY, paint);
left = (canvas.getWidth()/2) - 100;
top = (canvas.getHeight()/2) - 100;
right = (canvas.getWidth()/2) + 100;
bottom = (canvas.getHeight()/2) + 100;
canvas.drawRect(left, top, right, bottom, paint);
}
public boolean onTouch(View view, MotionEvent event) {
esferaX = (int)event.getX() - 100;
esferaY = (int)event.getY() - 100;
if (esferaX >= left && esferaY >= top && esferaX <= right && esferaY <= bottom){
return false;
}
invalidate();
return true;
}
}
答案 0 :(得分:1)
围绕super_esfera创建一个矩形
rect2 = new Rect(esferaX-100,esferaY-100,esferaX + 100,esferaY + 100);
围绕为碰撞创建的矩形创建一个矩形
rect = new Rect(左,上,右,下);
使用Rect类的intersects方法来查看是否发生碰撞
if (Rect.intersects(rect,rect2)) {
Log.i(getClass().getName(),"coliding now");
}