【问题标题】:libgdx pixel collision on very simple 2D game非常简单的 2D 游戏上的 libgdx 像素碰撞
【发布时间】:2017-09-26 18:08:13
【问题描述】:

我对 libgdx 和游戏开发非常陌生。我的任务是给我一个非常简单的 2D 游戏,它已经实现了矩形碰撞检测。

游戏只是由一个可以由玩家控制的方块组成,它位于墙内,其他分散在墙内的正方形。我现在需要在玩家方格和分散的方格/墙壁之间实现像素完美碰撞。

我最初尝试使用 Pixmap 并尝试检查当前坐标的像素对于播放器矩形以及与之碰撞的矩形是否透明,但无法正确实现代码。

我知道我必须在某个坐标处检查两个对象的像素颜色,看看它们是否都不是透明的以发生碰撞,但我遇到了麻烦。我花了很长时间在网上进行研究和查找,因此非常感谢任何有关如何执行此操作的帮助或建议!

public boolean entityCollision(Entity e1, Direction direction, float newX, float newY) {
    boolean collision = false;

    for(int i = 0; i < entities.size(); i++) {
        Entity e2 = entities.get(i);

        if (e1 != e2) {

            if (newX < e2.x + e2.width && e2.x < newX + e1.width &&
                newY < e2.y + e2.height && e2.y < newY + e1.height) {
                collision = true;

                int colorOne = player.getPixel((int)newX,(int)newY);
                int colorTwo = enemy.getPixel((int)e2.x,(int)e2.y);

                if (colorOne != 0 && colorTwo != 0) {
                  collision = true;
                  e1.entityCollision(e2, newX, newY, direction);
                }
            }
        }
    }

    return collision;
}

【问题讨论】:

    标签: java libgdx collision-detection


    【解决方案1】:

    看看 libgdx 的the Rectangle implementation。它允许您执行以下操作:

    Rectangle e1Rec = new Rectangle(e1.x, e1.y, e1.width, e1.height);
    Rectangle e2Rec = new Rectangle(e2.x, e2.y, e2.width, e2.height);
    
    if (e1Rec.contains(e2Rec)) {
       // Collision!
    }
    

    【讨论】:

    • 谢谢!我能够使用 .overlaps() 方法而不是 .contains() 让它工作
    【解决方案2】:

    如果您想与精灵发生碰撞,您可以获取精灵矩形并检查该矩形内的碰撞。

    sprite.getboundingrectangle().contains(x, y) ; //returns a boolean
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多