c++ - 小行星游戏 C++ 惯性

标签 c++

我试图让我的小行星在按下按钮后继续移动。

void Ship::applyThrust()

{

   _v.setX(_v.getX() - sin(2 * M_PI * (_angle / 360)) * 2.5); 

   _v.setY(_v.getY() + cos(2 * M_PI * (_angle / 360)) * 2.5); 

}

这是帮助我的船移动的公式。

_v.setX和_vsetY更新X和Y位置

M_PI 仅为 3.14。

_angle 是我用左右箭头键和

设置的旋转角度

2.5 是我希望它移动多少帧

我的船移动得很好,问题是我正在尝试模拟空间惯性并让我的船继续移动。

关于这方面的逻辑有什么想法吗?

谢谢,

最佳答案

在您的游戏循环中,您需要一个函数来根据船舶的 x 和 y 速度更新船舶的位置。您已接近获得船舶的新 x 和 y 坐标,但您没有考虑船舶的速度。当你施加推力时,获取你的速度的 x 和 y 分量,而不是你的新位置。您将有一个附加功能来更新位置,该功能应在游戏循环中按时间间隔调用 - 例如每次更新框架时。因此,您的applyThrust 函数实际上应该更新您的飞船速度。这意味着您需要将变量添加到您的 Ship 类中以获取您的船的位置和船的速度(如果您还没有的话)。为简单起见,我分解了位置和速度的分量,但为了清楚起见,您可能希望将它们存储在 vector 中:

class Ship 
{
    private float xpos, ypos; // current position of your ship
    private float velocityX, velocityY; // current velocity of your ship
}

然后,当您施加推力时,您会更改速度,并记住 applyThrust 仅在按下推力按钮时被调用,而不是每一帧,因为位置更新是:

void Ship::applyThrust()
{
    /* 
       Assume 1 total unit of thrust is applied each time you hit the thrust button
       so you break down the velocity into x and y components depending on the direction
       your ship is facing. 
    */    
    // thrustUnit is how much thrust each thrust button press gets you, it's arbitrary
    // and can be the 2.5 multiplier you're using in your question
    float thrustUnit = 1.0;

    // now get the x and y thrust components of velocity based on your ship's direction
    // assuming 0 degrees is pointing to the right
    float newVX, newVY = 0.0;        
    newVX = thrustUnit * cos(_angle);
    newVY = thrustUnit * sin(_angle); // radian conversion left out to save space

    // Update your ship's velocity
    updateVelocity(newVX, newVY);
}

updateVelocity 看起来像这样:(注意速度是相加的,所以它会继续漂移,除非在相反方向施加推力 - 就像它一样在无摩擦的介质中,例如空间)

void Ship::updateVelocity(newVX, newVY)
{
    // update the x component
    velocityX += newVX;
    velocityY += newVY;
}

所以现在您还需要一个 updatePosition 函数来考虑您的飞船速度。每次帧更新都会调用它:

void Ship::updatePosition()
{
    // add the x component of velocity to the ship's x position
    // assuming xpos and ypos are variables in the Ship class for tracking position
    xpos += velocityX;
    ypos += velocityY;
}

现在船的位置根据每个帧更新时的每个速度分量递增变化。您还可以使 thrustUnit 成为一个成员变量,以允许提升或降低推力分量以适应您的船速,并能够使用较小的 thrustUnit 或通过大型 thrustUnit 为其提供超高速。

祝你游戏顺利!

关于c++ - 小行星游戏 C++ 惯性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287803/

相关文章:

c++ - 以二进制方式使用 boost::asio::streambuf 进行顺序通信失败?

c++ - 通过名称访问结构变量

c++ - 期望在两个相同平台上构建两个共享库是否合理?

c++ - 如何将数据从一个 Windows 应用程序复制到另一个 Windows 应用程序?

c++ - 从临时对象返回左值引用

c++ - Boost.Spirit 可以在理论上/实践上用于解析 C++(0x)(或任何其他语言)吗?

c# - c++:使用类型作为 map /字典的键?

c++ - 如何在发布源代码之前隐藏 C++ 函数定义

c++ - 非 MFC CalcWindowRect()?

java - 写入在 Windows 下的 Java 应用程序中生成的 C++ 控制台应用程序