Accelerate Player with Rigidbody.AddForce
I'm making a third person project to learn Unity. I've imported a free humanoid model from the asset store and attached a player script to the model. In my FixedUpdate function, I apply a force to the model to make it move. Movement works. What I want to do now, is make it so that my player doesn't go from standing still to max speed instantly. I followed a tutorial and what it said makes sense, but it's not working. It said to apply a smaller force over many ticks to get the desired acceleration effect. Once masted, incorporate Time.deltaTime logic to really tweak the result.
What I have so far:
private void FixedUpdate()
{
// If we are not grounded, we cannot move
if (IsGrounded() && playerTryingToWalk)
{
// Calculate how fast we should be moving
// TargetVelocity will be a Vector3 (x, 0, y) where:
// x is either -1 or 1 depending on left or right
// y is either -1 or 1 depending on forward or backward
Vector3 targetVelocity = new Vector3(moveVector.x, 0, moveVector.y);
// Multiply the targetVelocity by the player's speed to get the real velocity we wish to achieve
targetVelocity *= playerSpeed;
// If we are pressing the boost button we are running, increase the target velocity again
if (playerBoosting)
{
targetVelocity *= playerRunMultiplier;
}
// Apply a force that attempts to reach our target velocity
// This is called in Start(): rb = GetComponent<RigidBody>();
Vector3 velocity = rb.velocity;
// Subtract our current velocity from our target velocity
// to see how much more velocity we need to achiever our target
Vector3 velocityChange = (targetVelocity - velocity);
Debug.Log(velocity);
Debug.Log(velocityChange);
// Don't apply the full force needed in the first tick,
// stretch it out over however many ticks it takes
// Player Acceleration is 1.0f
velocityChange.x = Mathf.Clamp(velocityChange.x, -playerAcceleration, playerAcceleration);
velocityChange.z = Mathf.Clamp(velocityChange.z, -playerAcceleration, playerAcceleration);
velocityChange.y = 0;
// Finally, apply the force needed to accelerate
rb.AddForce(velocityChange, ForceMode.VelocityChange);
}
}
The issue I'm having is that the code above does not push my player to the target velocity, it maxes out at whatever the playerAcceleration value is. As an example if my targetVelocity is 100 and my playerAcceleration is 10, my character velocity never goes above 10.
Something I noticed is that my two Debug.Log lines above always output the same thing.
Debug.Log(velocity); - Always outputs (0,0,0)
Debug.Log(velocityChange); - Always outputs (x, 0, y) where x and y are always +/- playerAcceleration depending on movement direction
Please help,
Dustin