我试图让我的小行星在按下按钮后继续移动。
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更好地控制它em> 或通过大型 thrustUnit 为其提供超高速。
祝你游戏顺利!
关于c++ - 小行星游戏 C++ 惯性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287803/