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.
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;
}
}