繁体   English   中英

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

[英]Collision detection, rectangle intersects at corner

我正在尝试学习碰撞检测在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);        
    }
}

这是一个非常简单的算法,用于两个矩形之间的碰撞。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM