This script allows you to jump when the Player character has a Character Controller.
To use it, create a new C# script named CCJump, paste in the code below, and attach to the Player.
To animate the character while jumping, optionally define a new Trigger parameter in the Animator, and enter its name into the Inspector's "Jump Trigger" field.
CCJump.cs:
using UnityEngine;
using AC;
public class CCJump : MonoBehaviour
{
[SerializeField] private float midAirTurnSpeed = 10f;
[SerializeField] private string jumpTrigger;
private Vector3 movingDirection = Vector3.zero;
private CharacterController controller;
private const float gravity = 10.0f;
private Char acCharacter;
private void Start ()
{
acCharacter = GetComponent <Char>();
controller = GetComponent <CharacterController>();
}
private void Update ()
{
if (controller.isGrounded && Input.GetButtonDown ("Jump") && KickStarter.stateHandler.IsInGameplay ())
{
acCharacter.motionControl = MotionControl.Manual;
movingDirection.y = KickStarter.settingsManager.jumpSpeed;
if (string.IsNullOrEmpty (jumpTrigger))
{
acCharacter.GetAnimator ().SetTrigger (jumpTrigger);
}
}
if (acCharacter.motionControl == MotionControl.Manual)
{
Vector2 moveKeys = KickStarter.playerInput.GetMoveKeys ();
Vector3 moveDirectionInput = (moveKeys.y * MainCamera.ForwardVector ()) + (moveKeys.x * MainCamera.RightVector ());
Quaternion lookRotation = Quaternion.LookRotation (moveDirectionInput, Vector3.up);
acCharacter.TransformRotation = Quaternion.Slerp (acCharacter.TransformRotation, lookRotation, Time.deltaTime * midAirTurnSpeed);
float flatSpeedMultiplier = KickStarter.playerInput.IsPlayerControlledRunning () ? (acCharacter.runSpeedScale / acCharacter.walkSpeedScale) : 1f;
flatSpeedMultiplier *= acCharacter.walkSpeedScale;
movingDirection = new Vector3 (moveDirectionInput.x * flatSpeedMultiplier, movingDirection.y, moveDirectionInput.z * flatSpeedMultiplier);
movingDirection.y -= gravity * Time.deltaTime;
controller.Move (movingDirection * Time.deltaTime);
}
}
private void LateUpdate ()
{
if (controller.isGrounded && !Input.GetButtonDown ("Jump"))
{
acCharacter.motionControl = MotionControl.Automatic;
}
}
}