C++ 和 SFML 中移动球与非移动球碰撞

问题描述 投票:0回答:0

所以,基本上我正在尝试使用 SFML 在 C++ 中实现基本重力模拟器,并且可行,但是我遇到了碰撞问题。有一个行星(重力源)-不可移动的球,没有任何速度,不改变其位置,其固定,并且我们有粒子-对重力源做出反应的可移动球。在某些时候,这两个球会发生碰撞,我正在尝试实现平滑的粒子和重力源的碰撞,但无论我做什么,都不是我想要实现的。

感谢所有帮助我解决这个问题的人!

这是我迄今为止创建的方法:

void updatePhysics(GravitySource& gravitySource, float deltaTime)
    {
        //Normal Vector
        float distanceX = gravitySource.getPos().x - pos.x;
        float distanceY = gravitySource.getPos().y - pos.y;

        //Distance between GravitySource and Particle
        float distance = std::sqrt(distanceX * distanceX + distanceY * distanceY);

        //Simplifying division to speed up calculations
        float inverseDistance = 1.f / distance;

        //Unit Vector
        float normalizedX = inverseDistance * distanceX;
        float normalizedY = inverseDistance * distanceY;

        float inverseSquareDropOff = inverseDistance * inverseDistance;

        //Calculating Acceleration
        float accelerationX = normalizedX * gravitySource.getStrength() * inverseSquareDropOff * deltaTime;
        float accelerationY = normalizedY * gravitySource.getStrength() * inverseSquareDropOff * deltaTime;

        //Updating Velocity
        vel.x += accelerationX;
        vel.y += accelerationY;

        //Updating Position
        pos.x += vel.x;
        pos.y += vel.y;

        //Updating Render Position
        relPos.x = pos.x - radius;
        relPos.y = pos.y - radius;

        //TODO: Make collision work properly!!!
        //Checking for collision
        if (distance <= radius + gravitySource.getRadius())
        {
            //Tangent Vector
            float tangentX = -normalizedY;
            float tangentY = normalizedX;

            //Velocity scalar in normal direction
            float normalScalarX = normalizedX * vel.x;
            float normalScalarY = normalizedY * vel.y;

            //New Unit Vector
            normalizedX = normalScalarX * normalizedX;
            normalizedY = normalScalarY * normalizedY;

            std::cout << vel.x << " " << vel.y << std::endl;
            vel.x = normalizedX + tangentX;
            vel.y = normalizedY + tangentY;
            std::cout << vel.x << " " << vel.y << std::endl;
        }
    }
class GravitySource
{
    sf::Vector2f pos;
    sf::Vector2f relPos;
    float strength;
    float radius;
    sf::CircleShape circleShape;
};
class Particle
{
    sf::Vector2f pos;
    sf::Vector2f relPos;
    sf::Vector2f vel;
    float radius;
    sf::CircleShape circleShape;
};
c++ game-physics sfml game-development
© www.soinside.com 2019 - 2024. All rights reserved.