Nothing is wrong in my script then also I am not able to make my player jump.
using UnityEngine;
public class ThirdPersonController : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public Transform checkSphere;
public LayerMask ground;
public Animator animator;
private float horizontal;
private float vertical;
private readonly float speed = 6f;
private readonly float turnSmoothTime = 0.1f;
private float turnSmoothVelocity;
private readonly float gravity = -9.8f;
private float downVelocity;
private bool onGround;
void Update()
{
Gravity();
Movement();
Jump();
}
public void Movement()
{
if (onGround)
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(speed * Time.deltaTime * moveDir.normalized);
animator.SetFloat("Speed", speed);
}
else
{
animator.SetFloat("Speed", 0f);
}
}
public void Gravity()
{
onGround = Physics.CheckSphere(checkSphere.position, 0.5f, ground);
if (!onGround)
{
animator.SetBool("Grounded", false);
animator.SetBool("FreeFall", true);
downVelocity -= gravity * Time.deltaTime;
controller.Move(downVelocity * Time.deltaTime * Vector3.down);
}
else if (onGround)
{
animator.SetBool("Grounded", true);
animator.SetBool("FreeFall", false);
downVelocity = 2f;
}
}
public void Jump()
{
if (Input.GetKeyDown("Jump"))
{
float jumpVelocity = Mathf.Sqrt(-2 * jumpHeight * gravity);
controller.Move(Vector3.up * jumpVelocity);
}
}
}