using UnityEngine;
public class CharacterController : MonoBehaviour
{
public float walkSpeed = 5f;
public float sprintSpeed = 10f;
public float jumpForce = 5f;
public float doubleJumpForce = 7f;
public Transform groundCheck;
public LayerMask groundMask;
private Rigidbody rb;
private bool isGrounded;
private bool canDoubleJump;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Check if the character is on the ground
isGrounded = Physics.CheckSphere(groundCheck.position, 0.2f, groundMask);
// Walk
float horizontalInput = Input.GetAxis("Horizontal");
Vector3 move = transform.right * horizontalInput * walkSpeed;
rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
// Sprint
if (Input.GetKey(KeyCode.LeftShift))
{
move = transform.right * horizontalInput * sprintSpeed;
rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
}
// Jump
if (Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
canDoubleJump = true;
}
else if (canDoubleJump)
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(Vector3.up * doubleJumpForce, ForceMode.Impulse);
canDoubleJump = false;
}
}
}
}