How to add opposite force of current direction?

I making Space shooter game, camera looking from bird view, my space ship turning around and goes in all direction by AddForce fucntion. i want to add braking sistem to decresing addforce in current direction until it reach zero. :slight_smile: can you write me that code?

this is my script

var speed : float = 10;
var rotationSpeed: float = 10;
var sideForce : float = 20;
var topSpeed : float = 20;

function Update()
{
	//Controls for ship...
	if(Input.GetKey("s") || Input.GetKey("0"))
	{
		rigidbody.AddRelativeForce(Vector3.back * speed * Time.deltaTime);
	}
	if(Input.GetKey("w") || Input.GetKey("1"))
	{
		rigidbody.AddRelativeForce(Vector3.forward * speed * Time.deltaTime);
	}
	
		if(Input.GetKey("q") || Input.GetKey("0"))
	{
		rigidbody.AddRelativeForce(Vector3.left * sideForce * Time.deltaTime);
	}
	
		if(Input.GetKey("e") || Input.GetKey("0"))
	{
		rigidbody.AddRelativeForce(Vector3.right * sideForce * Time.deltaTime);
	}
	
		if(Input.GetKey("a"))
	{
		transform.Rotate(Vector3.down * rotationSpeed * Time.deltaTime);
	}
	
		if(Input.GetKey("d"))
	{
		transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
	}
}

The rigidbody has a velocity vector indicating the direction and speed of its current movement.

If you want another vector pointing in the opposite direction? Just multiply by negative one. :slight_smile:

var opposite = -rigidbody.velocity;
rigidbody.AddForce(opposite * Time.deltaTime);

Maybe you want to control how hard you brake?

var opposite = -rigidbody.velocity;
var brakePower = 10;
var brakeForce = opposite.normalized * brakePower;
rigidbody.AddForce(brakeForce * Time.deltaTime);

The above might end up pushing backwards, when you’re almost stopped.

You could also scale down velocity:

var curSpeed = rigidbody.velocity.magnitude;
var newSpeed = curSpeed - 10 * Time.deltaTime;
if (newSpeed < 0) {
    newSpeed = 0;
}
rigidbody.velocity = rigidbody.velocity.normalized * newSpeed;

In this specific example, it might be simplest to simulate a brake by increasing the rigidbody’s drag:

if (braking) {
    rigidbody.drag = 20;
} else {
    rigidbody.drag = 5;
}

If any of this confuses you, I suggest reading up on the Vector3 and Rigidbody manual pages.

Is there a way to convert this into c#? I dont really have that much understanding of Javascript, but i have the exact same problem. :stuck_out_tongue: