Mid-air control with initial momentum using the CharacterController
xxxxxxxxxx
void ProcessMove()
{
if (_characterController.isGrounded)
{
// This implementation uses an empty gameObject controller by mouse input to set the orientation
moveDir = (_orientation.forward * rawDir.y + _orientation.right * rawDir.x);
airMove = moveDir; // add the movement direction to the air movment variable
}
else
{
// get the movement direction while mid-air
Vector3 raw = (_orientation.forward * rawDir.y + _orientation.right * rawDir.x);
/* get a modifier ratio by calculating the angle between the initial and mid-air movement directions.
* Clamp it to 90, then divide by 90. this means our ratio will be 0 if the vectors are parallel and
* 1 if they are perpendicular or opposite.
*/
float angRatio = Mathf.Clamp(Vector3.Angle(moveDir, raw), 0f, 90f) / 90f;
// calculate our mid-air movement if our movement input isn't zero
if (raw != Vector3.zero)
{
// add the movement to the air move variable
/* Negating our mid-air movement direction with our initial grounded movement direction helps
* cancelling out any further acceleration in the initial move direction.
*
* angRatio is applied last before we multiply everything by deltaTime
*
* airMoveModifier is a multiplier. 5 is a decent value for it
*/
airMove += (raw - moveDir) * moveSpeed * airMoveModifier * angRatio * Time.deltaTime;
// clamp the air movement to our maximum speed
if (airMove.magnitude > _moveSpeed)
{
airMove = airMove.normalized * moveSpeed;
}
}
}
// Grounded movment
if (_characterController.isGrounded)
{
finalMove = moveDir * moveSpeed
}
else // Mid-air movement
{
finalMove = (moveDir * moveSpeed) + airMove;
}
/* Apply the movement. Note that this implementation assumes the use of
* a seperate vector to handle our gravity
*/
_characterController.Move((finalMove + gravityVector) * Time.DeltaTime)
}