Add force cumulative

Hello there

I’m trying to make my player move with forces.

I have just used “AddRelativeForce” and it works fine.

But when I make my player move for some seconds in the same directions its speed is increased gradually.

How can I make my player move with forces but making the forces not to be accumulated.

Code: private void PlayerController() { if (to - Pastebin.com

Try use modeForce

Example

thisBody.AddForce(Vector3.froward * force, ForceMode.VelocityChange);

You can do it in two ways, the real world physics way by applying a drag force in the opposite direction, based on speed. Or by controlling movement by the velocity directly.

First method:

We use a simplified drag equation here:

DragForce = k*speed*speed, for (k some constant)

lets say we want our max speed to be 10, then we can work out when k*10*10 = 10 to get our constant k

in this case k = 10/100 = 0.1;

As we want our DragForce to have direction we need to multiply by the minus value of our velocity normalised.

Importantly:

velocity.normalized = velocity/(velocity.magnitude)

and

speed = velocity.magnitude

Hence:

directionalDrag = -0.1f*velocity.magnitude*velocity

Code becomes:

float k;
public float maxSpeed = 10;
Rigidbody rb;
Vector3 force;
Vector3 horizontalVelocity;

void Start(){
	k = 1/maxSpeed;
	rb = GetComponent<Rigidbody>();
}

private void PlayerController(){
	if (touchingGround== true) {
		force = Vector3.zero;
		if (Input.GetKey(KeyCode.W)){
			force += Vector3.forward * speed;
		}
		if (Input.GetKey(KeyCode.S)){
			force += Vector3.back * speed;
		}
		if (Input.GetKey(KeyCode.D)){
			force += Vector3.right * speed;
		}
		if (Input.GetKey(KeyCode.A)){
			force += Vector3.left * speed;
		}
		if (Input.GetKeyDown(KeyCode.Space)){
			force += Vector3.up * speed;
		}

		horizontalVelocity = rb.velocity;
		horizontalVelocity.y = 0;

		force += -k*horizontalVelocity.magnitude*horizontalVelocity;

		rb.AddRelativeForce(force);
	}
}

Second Method:

Set the velocity directly, this will look slightly less realistic possibly, unless you add some Mathf.Lerp’s!

Vector3 vel;

private void PlayerController(){
	if (touchingGround== true) {
		vel = Vector3.zero;
		if (Input.GetKey(KeyCode.W)){
			vel += transform.forward * speed;
		}
		if (Input.GetKey(KeyCode.S)){
			vel += -transform.forward * speed;
		}
		if (Input.GetKey(KeyCode.D)){
			vel += transform.right * speed;
		}
		if (Input.GetKey(KeyCode.A)){
			vel += -transform.right  * speed;
		}
		if (Input.GetKeyDown(KeyCode.Space)){
			vel += transform.up * speed;
		}

		rb.velocity = vel;
	}
}