【问题标题】:Near perfect collision in LibGdx JavaLibGdx Java 中的近乎完美碰撞
【发布时间】:2016-05-25 05:14:03
【问题描述】:

我试图让我的游戏中的碰撞完全完美。我正在测试的是,如果你与玩家撞墙,你就会停下来。我只实现了当玩家撞到墙的左侧时(当墙在玩家的右侧时)的碰撞代码。这是代码。

    if(entityOnRight){
        if(player.getPositionCorner(SquareMapTuples.BOTTOM_RIGHT).x -
                ent.getPositionCorner(SquareMapTuples.BOTTOM_LEFT).x > -.9f)
            player.setMovementBooleans(false, false, false, false);
        else
            player.setMovementBooleans(true, false, false, false);
    }

注意:如果我走得很慢,它会在我希望它停止的地方停止玩家,但如果走得快,它不会按照我想要的方式进行碰撞

本质上,代码说明如果墙在右侧,它将检查播放器矩形的右下角,减去墙的左下角,并检查两者之间的距离是否为0.001 . 0.001 几乎是一个不明显的距离,因此我使用该值。这是player.setMovementBooleans的代码

public void setMovementBooleans(boolean canMoveRight, boolean canMoveLeft, boolean canMoveUp, boolean canMoveDown){

    this.canMoveRight = canMoveRight;
    if(canMoveRight == false && moveRight)
        vel.x = 0;
}

Player 类中的 canMoveRight 布尔值(不在参数中)是允许您移动的原因,moveRight 是您尝试向右移动的原因。下面是一些可以更好地解释这些布尔值如何交互的代码:

//If you clicked right arrow key and you're not going 
    //Faster then the max speed

    if(moveRight && !(vel.x >= 3)){
        vel.x += movementSpeed;
    }else if(vel.x >= 0 && !moveRight){
        vel.x -= movementSpeed * 1.5f;
        System.out.println("stopping");
        //Make sure it goes to rest
        if(vel.x - movementSpeed * 1.5f < 0)
            vel.x = 0;
    }

和:

if(Gdx.input.isKeyPressed(Keys.D) && canMoveRight)
        moveRight = true;
    else
        moveRight = false;

所以总结一下,如果你点击“D”键,它可以让你开始移动。但是,如果布尔值 canMoveRight 为假,它不会让你感动。这是一张显示发生了什么的图片(玩家是黄色的,墙是绿色的)

如您所见,播放器比我想要的要走得更远。它应该在这一点停止:

非常感谢任何有关如何完成此操作的帮助!

【问题讨论】:

    标签: java libgdx


    【解决方案1】:

    也许你尝试的方式有点太复杂了:-)。我建议从头开始一种更简单的方法:将地图和播放器设为 com.badlogic.gdx.math.Rectangle 实例。现在,在代码的以下部分中,您进行检查,移动后玩家是否仍然在地图内,如果是则允许移动,如果不是,则不允许:

    if(Gdx.input.isKeyPressed(Keys.D){
        float requestedX, requestedY;
        //calculate the requested coordinates
        Rectangle newPlayerPositionRectangle = new Rectangle(requestedX, requestedY, player.getWidth(), player.getHeight());
        if (newPlayerPositionRectangle.overlaps(map) {
            //move the player
        } else {
            //move the player only to the edge of the map and stop there
        }
    }
    

    【讨论】:

    • 是的,但 .overLaps 方法是我要求的部分
    • 所以它回答了你的问题?
    • 对不起,我没有意识到重叠是一个实际的内置方法
    【解决方案2】:

    处理这些碰撞的最佳方法是使用像 Box2D 这样的物理引擎,它已经与 Libgdx 打包在一起。当 Box2D 中发生碰撞时,会触发一个事件,您可以轻松处理该事件。所以你应该看看here

    在没有物理的情况下实现此目的的另一种方法是使用表示玩家和墙壁的逻辑矩形(也可以是折线)并使用 libgdx 的 Intersector 类。 这是here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      相关资源
      最近更新 更多