Relative Movement & Momentum problem - Space sim

Hi,

We’ve been working on trying to move a spaceship in zero G. Using the engine we want to boost forward then rotate so that it flies backwards.

I can do that with this code below but it will always move it on the Z axis which is not the desirable result.

    transform.position += Vector3.forward * velocity * mass * Time.deltaTime;

We can get the ship to realistically move forward relative to the way it is facing using this script but with this we cannot then boost forward and rotate so that it flies backwards. As it naturally carries its forward momentum relative to the way it is facing.

    transform.position += transform.forward * velocity * mass * Time.deltaTime;

All velocity is this. When the controls are held down its incremented.

    velocity = currentVelocity += engineForce;

Is there a way to achieve what we are trying to achieve. Do I need to be using something like Transform.TransformDirection because I have never used that.

Any help or suggestions would be greatly appreciated.

Thanks in advance


EDIT:
The code is there, I feel like I need to be doing something else to it. Like copying the players facing rotation, applying the force and momentum to that copy so it wasn’t constantly updating the velocity in the direction the player is facing. If that makes sense.

The built-in Rigidbody component is superior to custom scripts in almost every way when it comes to simulating physics in Unity. I would add a Rigidbody to the ship GameObject and use AddForce() to move the ship around. You just need to uncheck ‘Use Gravity’ in the Rigidbody’s inspector, to simulate Zero G.

Engine.cs

using UnityEngine;

public class Engine : MonoBehaviour
{
	public float engineForce;

	void Update()
	{
		Rigidbody rb = GetComponent<Rigidbody>();
		rb.AddForce(transform.forward * engineForce);
	}
}

BUT, if you have a good reason not to use a Rigidbody, you could make your own sort of rigidbody script to handle velocity, like you were doing in your question.

CustomRigidbody,cs

using UnityEngine;

public class CustomRigidbody : MonoBehaviour
{
	public float mass;
	public float engineForce;
	private Vector3 velocity;

	void Update()
	{
		// F = m*a = m*dv/dt  therefore  dv = F*dt/m
		Vector3 deltaVelocity = transform.forward * (engineForce * Time.deltaTime / mass);
		velocity += deltaVelocity;

		// v = ds/dt  therefore  ds = v*dt
		Vector3 deltaDisplacement = velocity * Time.deltaTime;
		transform.position += deltaDisplacement;
	}
}