在 SFML 2.4 中使用碰撞检测来增加游戏分数的问题

Problem using collision detection to increment the game score in SFML 2.4

我正在制作一个 flappy bird 游戏,只是为了了解如何使用 SFML 2.4 和 C++ 制作游戏。我有一个计分系统,每当小鸟精灵与一个看不见的管道相交时,它应该将分数增加 1。然而,分数并没有增加 1,而是达到了 57 和 60 左右。非常感谢任何让这个工作发挥作用的想法。

int main()
{
    int score = 0;

    float PipeInvisi = 200.0;

    while(window.isOpen())
    {
        if (state == State::PLAYING)
        {
            // Setup the Invisible Pipe for Movement
            if (!PipeInvisbleActive)
            {
                // How fast is the Pipe
                spriteInvisi.setPosition(905, 0);
                PipeInvisbleActive = true;
            }
            else
            {
                spriteInvisi.setPosition(spriteInvisi.getPosition().x - (PipeInvisi * dt.asSeconds()), spriteInvisi.getPosition().y);
                // Has the pipe reached the right hand edge of the screen?
                if (spriteInvisi.getPosition().x < -165)
                {
                    // Set it up ready to be a whole new cloud next frame
                    PipeInvisbleActive = false;
                }
            }

            // Has the Bird hit the invisible pipe
            Rect<float> Birdie = spriteBird.getGlobalBounds();
            Rect<float> Paipu5 = spriteInvisi.getGlobalBounds();
            if (Birdie.intersects(Paipu5))
            {
                // Update the score text
                score++;
                std::stringstream ss;
                ss << "Score = " << score;
                scoreText.setString(ss.str());
                clock.restart();
            }
        }
    }
}

假设您的问题源于不断的交集,您可以引入一个简单的标记来标记交集。

bool isBirdIntersectingPipe = false;

然后在您的游戏循环中,您可以像这样检测交叉点的开始。

if (birdRect.intersects(pipeRect)) // Intersection this frame.
{
    if (!isBirdIntersectingPipe) // No intersection last frame, so this is the beginning.
    {
        ++score;
        isBirdIntersectingPipe = true;
    }

    // Still intersecting, so do nothing.
}
else // No intersection this frame.
{
    isBirdIntersectingPipe = false;
}

理想情况下,您会有一个专门的碰撞系统甚至物理系统来跟踪场景中的所有对象,但在这种情况下,像这样的简单解决方案就足够了。