Java 2D游戏 - 仅在玩家在地面时才跳跃

时间:2015-12-12 20:01:58

标签: java collision-detection

我正在制作2D平台游戏,只是添加了重力和放大器。跳跃。

它的工作原理应该如此,但是,如果在玩家完成跳跃后空格键仍然按下,则玩家只能在半空中继续跳跃。

我知道我需要检查玩家是否真的在地面上,但是当我这样做时,它总是以“跳跃法”中所述的方式返回' false'

// Controls both falling and the jumping action.
// The MapObject list is a collection of every object the player can
// collide with on that map. Currently it only contains a single 'ground' object.

    public void fall(ArrayList<MapObject> objects)
{
    int distance = 0;

    if (jumpTicks > 0)
    {
        float jumpHeight = jumpSpeed * (jumpTicks / maxJumpTicks);
        System.out.println(jumpTicks + "/" + maxJumpTicks + " = " + jumpHeight);
        y -= jumpHeight;
        jumpTicks--;
    }
    else
    {
        for (MapObject obj : objects)
        {
            if (this.y + this.height >= obj.y)
            {
                // This cancels falling if the player's feet are on top
                // of the ground, but for some reason setting an 'isOnGround'
                // boolean to 'true' here and checking for it in the 'jump()'
                // method does not work, it's always 'false'.
                return;
            }
            distance = obj.y - (this.y + this.height);
        }
        if (distance > fallSpeed)
        {
            y += fallSpeed;
        }
        else
        {
            y += distance;
        }

    }
}

// This doesn't make the player jump, it just adds jump time to the player
// if it's not already jumping.

public void jump()
{
    if (jumpTicks > 0)
    {
        return;
    }
    this.jumpTicks = maxJumpTicks;
    this.jumpSpeed = 10;
}

1 个答案:

答案 0 :(得分:1)

在更改速度之前,请检查他的y楼层值

function jump() {
    if (jumpTicks > 0) {
        return;
    }
    if (this.y === floorY) {
        this.jumpTicks = maxJumpTicks;
        this.jumpSpeed = 10;
    }
}