I’m trying to figure out why my jump is not working for my 3rd person jump code. I’m currently getting a NaN on my jump velocity Vector3 whenever I press space, resulting in the character freezing wherever they are. I’m very new to this and I tried combining Brackey’s 3rd person movement tutorial with his jump from his first person movement tutorial but the math confuses me.
using System;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float Speed = 6f;
public float gravity = -9.81f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public bool isGrounded;
public Vector3 velocity;
public Vector3 movDir;
private Vector3 moveNormalized;
private Vector3 finalVelocity;
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
velocity.y += gravity * Time.deltaTime;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(velocity.y * -9.81f * gravity);
}
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);
movDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
moveNormalized = movDir.normalized * Speed;
finalVelocity = new Vector3(moveNormalized.x, velocity.y, moveNormalized.z);
controller.Move(finalVelocity * Time.deltaTime);
}
}
}