To add sprinting and crouching functionalities to your player movement script, we'll introduce variables to control sprint and crouch speeds, handle input for sprinting and crouching, and adjust the player's speed and character controller's height accordingly. Here's the improved script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public float speed = 12f; // Base walking speed
public float gravity = -9.81f * 2;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 Velocity;
bool isGrounded;
bool isMoving;
private Vector3 lastPosition = new Vector3(0f, 0f, 0f);
// Sprint and crouch variables
public float walkSpeed = 12f; // Normal walking speed
public float sprintSpeed = 18f; // Sprinting speed
public float crouchSpeed = 6f; // Crouching speed
private float currentSpeed;
private bool isSprinting = false;
private bool isCrouching = false;
private float originalHeight;
public float crouchHeight = 1f; // Height when crouching
void Start()
{
controller = GetComponent<CharacterController>();
originalHeight = controller.height;
currentSpeed = walkSpeed; // Initialize currentSpeed to walkSpeed
}
void Update()
{
// Ground check
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
// Reset default velocity if grounded
if (isGrounded && Velocity.y < 0)
{
Velocity.y = -2f;
}
// Handle sprint input
if (Input.GetKey(KeyCode.LeftShift) && !isCrouching)
{
isSprinting = true;
}
else
{
isSprinting = false;
}
// Handle crouch input (only when grounded)
if (Input.GetKey(KeyCode.LeftControl) && isGrounded)
{
isCrouching = true;
}
else
{
isCrouching = false;
}
// Adjust speed based on sprinting or crouching
if (isCrouching)
{
currentSpeed = crouchSpeed;
}
else if (isSprinting)
{
currentSpeed = sprintSpeed;
}
else
{
currentSpeed = walkSpeed;
}
// Adjust controller height when crouching
if (isCrouching)
{
controller.height = Mathf.Lerp(controller.height, crouchHeight, Time.deltaTime * 8f);
}
else
{
controller.height = Mathf.Lerp(controller.height, originalHeight, Time.deltaTime * 8f);
}
// Get movement inputs
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
// Create movement vector
Vector3 move = transform.right * x + transform.forward * z;
// Move player
controller.Move(move * currentSpeed * Time.deltaTime);
// Check if player can jump
if (Input.GetButtonDown("Jump") && isGrounded && !isCrouching)
{
// Jump
Velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// Apply gravity
Velocity.y += gravity * Time.deltaTime;
// Move player vertically
controller.Move(Velocity * Time.deltaTime);
// Update movement state
if (lastPosition != gameObject.transform.position && isGrounded)
{
isMoving = true;
}
else
{
isMoving = false;
}
lastPosition = gameObject.transform.position;
}
}
Explanation of the Improvements:
-
Sprint Functionality:
- Variables Added:
public float sprintSpeed = 18f; // Speed while sprinting.
private bool isSprinting = false; // Tracks if the player is sprinting.
- Input Handling:
- Checks if the Left Shift key is held down to enable sprinting:
Input.GetKey(KeyCode.LeftShift).
- Speed Adjustment:
- When sprinting,
currentSpeed is set to sprintSpeed.
- The player cannot sprint while crouching (handled in input check).
-
Crouch Functionality:
- Variables Added:
public float crouchSpeed = 6f; // Speed while crouching.
private bool isCrouching = false; // Tracks if the player is crouching.
private float originalHeight; // Stores the original height of the character controller.
public float crouchHeight = 1f; // Height of the controller when crouching.
- Input Handling:
- Checks if the Left Control key is held down to enable crouching:
Input.GetKey(KeyCode.LeftControl).
- Crouching is only allowed when the player is grounded.
- Speed and Height Adjustment:
- When crouching,
currentSpeed is set to crouchSpeed.
- The character controller's height is smoothly adjusted using
Mathf.Lerp for a smooth transition.
- If not crouching, the controller's height is reset to the original height.
-
Optimizations:
- Introduced
currentSpeed to manage and switch between different movement speeds based on the player's state.
- Used
Mathf.Lerp for smooth height transitions when crouching and standing up.
- Ensured that the player cannot sprint while crouching or jump while crouching for realistic movement behavior.
Note: The script assumes that there are no obstacles above the player when standing up from a crouch. If you need to prevent the player from standing up under low ceilings, you should implement an additional check to see if there's enough space above before allowing the player to stand up.