【问题标题】:Libgdx Rectangle Wall CollisionLibgdx 矩形墙碰撞
【发布时间】:2017-01-14 16:08:17
【问题描述】:

我一直在尝试为 Libgdx 中的矩形查找/创建碰撞检测,但我似乎无处可去。我有一个名为 bucket 的矩形,宽度和高度为 64,还有一个名为 wall 的矩形,宽度和高度为 64。我正在努力做到这一点,以便玩家不会穿过矩形,并且可以在粘在墙上的同时继续移动而没有逐步通过或随机传送。我的方法在有 1 个块时有效,但当有多个块时它就会中断并且不起作用。

我知道这种方法很丑,但它只是实验

private void checkCollisions(Rectangle bucket, Wall wall){
    if(bucket.overlaps(wall.getRectangle())){
        if(bucket.x > wall.getRectangle().x - 64 && bucket.x < wall.getRectangle().x - 55){
            //collision with right side
            bucket.x = wall.getRectangle().x - 64;
        }
        if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x + 55){
            //collision with left side 
            bucket.x = wall.getRectangle().y + 64;
        }                           
        if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y + 55){
            //collision with top side 
            bucket.y = wall.getRectangle().y + 64;
        }                             
        if(bucket.y > wall.getRectangle().y - 64 && bucket.y < wall.getRectangle().y - 55){
            //collision with bottom side
            bucket.y = wall.getRectangle().y - 64;
        }
    }
}

如果有人能指出我正确的方向或分享一些对我有帮助的代码,我将不胜感激。

【问题讨论】:

    标签: libgdx collision-detection rectangles


    【解决方案1】:

    在LibGDX中查看碰撞检测时,您必须首先注意默认 LibGDX 坐标系的两个重要方面。

    • 绘制图像时,其 (x, y) 坐标为图像的左下角
    • (0,0) 是屏幕的左下角

    使用此信息,我们可以将您的碰撞逻辑修正为以下内容:

    private void checkCollisions(Rectangle bucket, Wall wall){
        if(bucket.overlaps(wall.getRectangle())){
            if(bucket.x + 64 > wall.getRectangle().x && bucket.x < wall.getRectangle().x){
                //collision with right side of bucket
            }
            if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x){
                //collision with left side of bucket
            }                           
            if(bucket.y + 64 > wall.getRectangle().y && bucket.y < wall.getRectangle().y){
                //collision with top side of bucket
            }                             
            if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y){
                //collision with bottom side of bucket
            }
        }
    }
    

    此方法将确定 bucket 的哪一侧检测到与默认 LibGDX 坐标系的冲突。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      相关资源
      最近更新 更多