在LibGdx Java

时间:2016-05-25 05:14:03

标签: java libgdx

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

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

canMoveRight类中的Player布尔值(不在参数中)允许您移动,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;

所以要给出摘要,如果你点击&#34; D&#34;键,它允许你开始移动。但是,如果布尔值canMoveRight为false,则不会移动您。这是一张显示发生了什么的图像(玩家是黄色,墙是绿色)

enter image description here

正如你所看到的,玩家走得更远,然后我想要它。它应该在此时停止:

enter image description here

非常感谢任何有关如何实现这一目标的帮助!

2 个答案:

答案 0 :(得分:1)

处理这些碰撞的最佳方法是使用像Box2D这样的物理引擎,它已经包含了Libgdx。当Box2D发生冲突时,事件会被触发,您可以轻松处理该事件。所以你应该看看here

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

答案 1 :(得分: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
    }
}