Android Studio碰撞

问题描述:

我有一个位图,我随着触摸事件和屏幕中间的矩形移动。有人可以告诉我为什么位图和矩形不会碰撞?我在碰撞主题上很新颖。Android Studio碰撞

谢谢。

的代码:

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; 
} 

}

创建围绕super_esfera

RECT2 =新的Rect(esferaX-100,esferaY-100,esferaX + 100,esferaY + 100)一个矩形;

创建您周围是否有碰撞

RECT =新的矩形(左,上,右,下)创造了RECT一个矩形;

使用相交的Rect类的方法,以查看是否碰撞

if (Rect.intersects(rect,rect2)) { 
    Log.i(getClass().getName(),"coliding now"); 
    } 
+0

您好,感谢aswer,我改变RECT2为“RECT2 =新的Rect(esferaX,esferaY,esferaX + 200,esferaY + 200) ;”它的工作原理。 –