Quantcast
Channel: Questions in topic: "addforce"
Viewing all articles
Browse latest Browse all 1264

AddForce for spaceship acceleration, but with max speed

$
0
0
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

Viewing all articles
Browse latest Browse all 1264

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>