【问题标题】:Collision detection, rectangle intersects at corner碰撞检测,矩形在拐角处相交
【发布时间】:2014-11-22 21:35:01
【问题描述】:

我正在尝试了解碰撞检测在 android 中的工作原理,并且我正在使用 Android 矩形进行此操作。

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

下面是我正在使用的代码的 sn-p:

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

【问题讨论】:

    标签: java android collision


    【解决方案1】:

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

    x1+宽度1

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

    【讨论】:

    • 如果您能找出原始代码中的问题,解释如何解决问题以及您选择这样做的原因,这个答案可能会更好。
    • 我想你误会了,我需要检测哪个墙壁 shape1 撞到 shape2,无论是顶部、左侧还是底部。
    • @JasonC 哎呀,真的很抱歉,伙计们,我想我已经有点累了。正在编辑它。
    • 加上 rect1.intersect(rect2) 将是简单碰撞检测的更好解决方案
    • @mk_89 是的,我的帖子真的很无脑。我很抱歉。通过快速查看代码,我猜你的问题是,你正在使用 && 运算符 - 但你的表达不会是真的,因为你正在评估 "s1.y+s1.height > s2.y && s1.y
    猜你喜欢
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多