0
votes

I'm trying to learn how collision detection works in android and I am doing so using Android rectangles.

I need to be able to detect a collision of the second rectangles top, left and bottom walls but the issue is that the first rectangle is able to go straight in to the second rectangle through the top left corner.

Below is a snippet of the code that I am using:

Snippet from GameView2 class:

private Shape s1 = new Shape(this, Color.BLACK, 0, 100, 50, 50);
private Shape s2 = new Shape(this, Color.BLUE, 200, 100, 50, 50);

@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);

    this.drawBackground(canvas);
    s1.onDraw(canvas);
    s2.onDraw(canvas);
    s1.x+=s1.vx;
    s1.y+=s1.vy;

    //left wall collision
    if(s1.x+s1.width==s2.x  &&  s1.y+s1.height > s2.y  &&  s1.y < s2.y + s2.height){
        s1.vx = 0;
    }

    //top wall
    else if(s1.y+s1.height==s2.y  &&  s1.x+s1.width > s2.x  &&  s1.x < s2.x+s2.width){
        s1.vy = 0;
    }

    else{
        s1.vx = 2;
    }
}

Shape class:

public class Shape{
    protected GameView2 game_view;
    protected int x;
    protected int y;
    protected int vx;
    protected int vy;
    protected int width;
    protected int height;
    protected int color;

    public Shape(GameView2 game_view, int color, int x, int y, int width, int height) {
        this.game_view = game_view;
        this.x = x;
        this.y = y;
        this.vx = 2;
        this.vy = 0;
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public Rect getRect(){
        return new Rect(x, y, x + width, y + height);
    }

    public void onDraw(Canvas canvas){

        Paint paint = new Paint();
        Rect rec = new Rect(x, y, x + width, y + height);
        paint.setColor(color);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(rec, paint);        
    }
}
1

1 Answers

-1
votes

Here is a really simple algorithm for collision between two rectangles.

x1+width1 < x2 || x2+width2 < x1 || y1+height1 < y2 || y2+height2

If the statement above is true, no collision occurs. Else, the two rectangles are colliding.