在 SFML 中移动球

Moving a ball in SFML

本文关键字:移动 SFML      更新时间:2023-10-16

我正在使用SFML制作乒乓球游戏,球是一个正方形。我看了教程,由于某种原因,我无法让我的球移动。我使用 cout 语句来检查球的位置,但它只是输出其初始位置。我怀疑我的数学有问题...但是球应该移动。

void ball_traits(sf::RectangleShape ball, sf::RectangleShape leftPaddle)
{
    double ballSpeed = 5;
    int angle = 90;
    //Scale X and Y will give the angle
    double scaleX = cos(angle);
    std::cout << scaleX << std::endl;
    double scaleY = sin(angle);
    double velocityX = scaleX * ballSpeed;
    double velocityY = scaleY * ballSpeed;
    //take original position
    double moveX = ball.getPosition().x;
    double moveY = ball.getPosition().y;
    sf::Clock clock;
    double elapsed = clock.restart().asSeconds();
    moveX += velocityX  * elapsed;
    moveY += velocityY * elapsed;
    std::cout << moveX << std::endl;
    std::cout << moveY << std::endl;
    ball.move(moveX,  moveY);
}

我只是想被推向正确的方向。这是我的第一个游戏,我的 c++ 技能有点生疏。[更新]我忘了通过参考(脸掌)传递对象。

我认为经过的时间非常非常接近于零。它是零。是的。您应该将时钟声明为全局变量。

并且您必须将弧度用于 sin 和 cos 函数。