I’m trying to add the ability to jump to my CharacterController script, but it doesn’t seem to work right.
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThirdPersonController : MonoBehaviour
{
public CharacterController controller;
public Transform camera;
public float characterSpeed = 6f;
public float jumpSpeed = 2.0f;
public float gravity = 10.0f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
Vector3 moveDir = Vector3.zero;
bool jumping = false;
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.sqrMagnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
}
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
moveDir.y = jumpSpeed;
}
moveDir.y -= gravity * Time.deltaTime;
controller.Move(moveDir.normalized * characterSpeed * Time.deltaTime);
}
}
It only lets me jump while the CharacterController is motionless, but I’d like to be able to jump while for example moving forward.