Hey im wondering how i would extend unity’s character controller to handle acceleration.
Heres an example of the behaviour im aiming for:
Sorry for the shity picture. Let’s say this takes place in space. The red arrow is a force aplied to the ball, the gray line is the default path the ball would take with unitys character controller. The green line is
what im trying to make happen, so the balls looses its force when it hits the wall, but doesnt stop in the
direction that didn’t hit.
This could easily be done by using a rigidbody, but i need it working with unity’s character controller. Im not really sure how to procceed with this so any help is apreaciated. Thanks.
*Edit i figured it out. I find it how far the character actually moved by subtracting the objects position last frame with the new position. Then i just apply that to my speed.
Are you sure you do not want a Rigidbody? It would be easier. A CharacterController is just not made to have inertia.
If you still want to keep doing this, a solution would look like this:
Vector3 velocity = characterController.velocity;
Vector3 input = new Vector3(
Input.GetAxis("Horizontal"),
0f,
Input.GetAxis("Vertical");
//Warning: change in framerate may cause change in speed
velocity += input * playerAcceleration * Time.deltaTime;
velocity *= dragFactor;
velocity.y -= gravity * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime)
dragFactor
needs to be a float going from 1 to 0, depending on how fast you want your character to lose accumulated speed. This will also limit the maximum speed.
playerAcceleration
changes how fast the player can accelerate, obviously. But increasing it will also increase the maximum speed.
gravity
is self explenatory.
Because this is all running on Update, this will mean that a change of framerate will change the behaviour of just about everything. A higher framerate will mean higher acceleration, higher drag, and higher gravity, even with the * deltaTime
. And I don’t think CharacterController.velocity works with FixedUpdate.