繁体   English   中英

LibGdx Java中接近完美的碰撞

[英]Near perfect collision in LibGdx Java

我正在尝试使游戏中的碰撞达到完美。 我正在测试的是,如果您与播放器撞墙,您会停下来。 我仅在玩家击中墙的左侧(墙在玩家的右侧)时实现了碰撞代码。 这是代码。

    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为false,则不会移动您。 这是显示发生情况的图像(玩家是黄色,墙壁是绿色)

在此处输入图片说明

如您所见,播放器比我想要的远了。 它应该在此时停止:

在此处输入图片说明

非常感谢您找出如何完成此操作的帮助!

处理这些冲突的最佳方法是使用已经随Libgdx一起提供的物理引擎,例如Box2D。 当Box2D中发生冲突时,将触发一个事件,您可以轻松地处理该事件。 因此,您可能应该在这里看看。

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

也许您尝试的方法有点太复杂了:-)。 我建议从头开始采用一种更简单的方法:将地图和播放器设为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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM