- Home /
AddForce for spaceship acceleration, but with max speed
Hi. So in a top down space shooter, with movement controls very similar to Asteroids (classic) I'm using the following code to move my ship forward when I press the up arrow, and to rotate with left/right:
void FixedUpdate ()
{
playerSpeed = rigidbody2D.velocity.sqrMagnitude;
if(Input.GetButton("ForwardThrust"))
{
ForwardThrust();
}
if (Input.GetButton("RotateLeft"))
{
RotationalThrust(1);
}
if (Input.GetButton("RotateRight"))
{
RotationalThrust(-1);
}
}
//MOVEMENT FUNCTIONS
void ForwardThrust()
{
if(playerSpeed < 50) //hard coded
{
rigidbody2D.AddForce (transform.up * accelerationRate);
}
}
void RotationalThrust(float direction)
{
transform.Rotate (0.0f, 0.0f, turnRate * direction /damping);
}
When I reach a speed of 50 (desired) the function won't add any more force. The problem is that to slow down, I should be able to turn 180 degrees and press up again to add force, but now in the opposite direction, to slow me down. I can't do this though because my playerSpeed (rigidbody.velocity.sqrmagnitude) says I'm going at the max speed, and can't add more force, even though now it'd be slowing me down, instead of bringing my world speed over 50.
Can I somehow bring the direction I'm facing/travelling into the calculation? Or could I remove the 'if(playerSpeed < 50)' line and just cap a max speed somewhere in fixedUpdate? I haven't been able to get a Mathf.Clamp to work though. I imagine either of those 2 solutions would give me the desired effect, but I don't know how to do them.
Oh, as a workaround I have some drag in there so that my speed does naturally drop below 50, so then I CAN accelerate in the other direction again, but I don't want to use drag at all.
Thanks guys Kevin
Answer by Pyrian · Oct 19, 2014 at 06:24 PM
When the velocity is too high, just set the velocity to the normalized velocity (Vector3.Normalized) times your max velocity (square root of 50).
Answer by JtheSpaceC · Oct 19, 2014 at 10:59 PM
Thanks. Based on that I appear to have it working by updating the Forward movement function.
void ForwardThrust()
{
rigidbody2D.AddForce (transform.up * accelerationRate);
if(playerSpeed > maxForwardThrust)
{
rigidbody2D.velocity = Vector3.Normalize(rigidbody2D.velocity) * Mathf.Sqrt(50);
}
}