Search code examples
androidandroid-studiobitmapcollisionrect

Android Studio Collision


i have a bitmap that i move with the on touch event and a rect in the middle of the screen. Could someone tell my why the bitmap and the rect doesn´t collide? I'm very new in the collision subject.

Thanks.

The code:

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

}


Solution

  • Create a rect around super_esfera

    rect2 = new Rect(esferaX-100,esferaY-100,esferaX+100,esferaY+100);

    create a rect around the rect you created for collision

    rect = new Rect(left,top,right,bottom);

    use intersects method of Rect class to see if colliding

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