碰撞检测,矩形在拐角处相交

时间:2014-11-22 21:35:01

标签: java android collision

我正在尝试学习如何在Android中进行碰撞检测,而我正在使用Android矩形。

我需要能够检测到第二个矩形顶部,左侧和底部墙壁的碰撞,但问题是第一个矩形能够通过左上角直接进入第二个矩形。

以下是我正在使用的代码片段:

来自GameView2类的

片段:

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

形状类:

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 个答案:

答案 0 :(得分:-1)

这是一个非常简单的两个矩形碰撞算法。

x1 + width1&lt; x2 || x2 + width2&lt; x1 || y1 + height1&lt; y2 || Y2 +身高2

如果上述陈述为真,则不会发生冲突。否则,两个矩形会发生碰撞。