Change direction of rigidbody when force is no longer being applied
Hi,
I'm creating a basic spaceship style movement system and and am moving the object using AddForce applied to its Rigidbody when a 'thrust' key is held down. The direction of the force is based on the forward direction of its camera, in First Person which is controlled by the mouse (i.e. it moves in the direction it is looking). The force is only applied when the thrust key is pressed down, which means that if the mouse is moved around after the key is released, the ship will continue to move in the direction in which the force was applied, not where it is currently looking. In basic terms:
shipRB.AddForce(cameraTrans.forward * ThrustSpeed);
I was wondering how I might be able to change the direction of the Rigidbody and have it turn/rotate and continue to move in the direction the camera is looking in, even when the key has been released.
Any help would be great - thanks in advance.
Answer by Dibbie · Jun 14, 2016 at 07:36 AM
In your Update, you could try checking if the rigidbody's magnitude is less then your thrust speed. if(shipRB.velocity.magnitude <= ThrustSpeed){//make magic happen}
Answer by asimov · Jun 14, 2016 at 10:14 AM
Hi Dibbie - thanks for the suggestion!
But what is the magic that I need to happen to make the Rigidbody move in the direction that the camera's forward is pointing in after a force has been applied? :D
Well, it depends on how you want to handle your speed, but one easy way would be something like shipRB.velocity = -Camera.main.transform.forward * Time.deltatime;
which when you specify an object (like the camera)'s transform, you can access that objects directional variables such as the cameras "forward", ins$$anonymous$$d of Unity's "forward", and can apply that Vector3 to the velocity of your Rigidbody, which takes a Vector3 - the negative in front specifies, "move in the cameras REVERSE forward" and the opposite of forward is backward.
And if youd want it to gradually reduce speed and then start moving back (like cars do in GTA when you all of a sudden start trying to reverse, it looses all momentum first before going backward), then ins$$anonymous$$d of =, you would use += or -=.
You could also apply the same logic with Translate, or altering the position of your player specifically, etc... Theres tons of way you could do what your trying to achieve.