我试图在我的SFML Platformer中实现双跳,但它不能按照预期的方式工作

时间:2014-01-04 23:44:43

标签: c++ sfml

我正在尝试使用SFML for C ++制作平台游戏,但我无法按下按钮才能正常工作。试图双跳不起作用,按住跳跃按钮使我的角色不断跳跃。非常感谢帮助。

#include <SFML/Graphics.hpp>

sf::RenderWindow window(sf::VideoMode(200, 200), "Platformer");
float positionX = 100.0;
float positionY = 175.0;
float velocityX = 0.0;
float velocityY = 0.0;
float gravity = 1.3;
bool onGround = false;
sf::RectangleShape player(sf::Vector2f(5, 5));
sf::RectangleShape block(sf::Vector2f(5, 20));
int jumpCounter = 0;


void MoveLeft()
{
    velocityX = -12;
}

void MoveRight()
{
    velocityX = 12;
}

void StartJump()
{
    if (!onGround && jumpCounter == 0)
    {
        velocityY = -12;
        jumpCounter = 1;
    }
    if(onGround)
    {
        velocityY = -12;
        onGround = false;
        jumpCounter = 1;
    }
}

void EndJump()
{
    if(velocityY > -6)
        velocityY = -6;
}

void Update()
{
    velocityY += gravity/400;
    positionY += velocityY/400;
    positionX += velocityX/400;

    if(positionY > 195.0)
    {
        positionY = 195.0;
        velocityY = 0.0;
        onGround = true;
    }

    if(positionX > 195)
    {
        positionX = 195.0;
    }
    if(positionX < 0)
    {
        positionX = 0;
    }
    player.setPosition(positionX, positionY);
    velocityX = 0.0;
    if (onGround)
        jumpCounter = 0;
}

void Render()
{
    window.clear();
    window.draw(player);
    window.display();
}

int main()
{
    window.setKeyRepeatEnabled(false);
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event));
        Update();
        Render();
        if (event.type == sf::Event::Closed)
            window.close();
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
            StartJump();
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            MoveLeft();
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            MoveRight();

    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

sf::Keyboard::isKeyPressed()返回提供的密钥的当前状态。如果当前按下了该键,则为true;如果不是,则为false

当用户点击向上键时,它通常会在若干帧中保持按下状态。在每个帧上,测试是否按下了向上,并调用StartJump()。因此,按UP一次多次调用StartJump()。这会立即耗尽两次跳跃,因此您无法实际进行第二次跳跃。

您可能会有更多的运气听取与按下UP键相对应的sf::Event。每个完整的按键只会有一个这样的事件。