Adding force to RigidBody2D and at the same time make sure velocity is always in the direction of transform.up


I have a 2D spaceship that fly around and it occasionally encounters some asteroids (or other ships) and the way I have implemented this is by converting user input to a Vector2D like this:

Vector2 movement = new Vector2(0, currentPlayerSpeed);

The “currentPlayerSpeed” is calculated by the ship max speed and added in a acceleration over time, and I then add that Vector2D to the ships transform in the Update method like this (the ship always fly “up” relative to its own rotation):


I rotate the ship based on input (and added in some max rotation force) and the ship always fly in the direction of “up” with the current velocity, and this means that it does not fly even the the least sideways never ever. This is the way I want it to work, but… I would also like the ship to bounce of any asteroids (or other ships) it hits and I would like to use the build in physics for this.

I have converted my Update to FixedUpdate and I now do this to move the ship instead:

rigidbody2D.AddForce (transform.up * currentPlayerSpeed);
if(rigidbody2D.velocity.magnitude > maxShipSpeed)
	rigidbody2D.velocity = rigidbody2D.velocity.normalized * maxShipSpeed;

So with this I get the bounce off effect I want, but obviously the ship now fly sideways most of the time as the force is not directly translated to the ships velocity and manipulating the rigidbody2D.velocity directly gives me strange results so I have no idea how to do this. I have tried with the following code:

float magnitude = rigidbody2D.velocity.magnitude;
rigidbody2D.velocity = transform.up * magnitude;

and this makes the ship fly as I want it to, but obviously it also cansels out the collision forces so I am back to square zero. Any help/ideas are welcome as I am quite stuck with this.

Thank you

The way that I would go about doing this would be to stick with constraining the user input movement to the Y axis (like you did first) and then have event based physics on collision. E.G.

void OnCollisionEnter(Collision col)
	//calculate the rigidbody.AddForce here based on the data recieved from col
	//this way the Physics is still applied, but the USER input is still only the Y axis