Okay, here is a basic FPS movement script for Unity using the CharacterController component, which is standard practice for FPS movement in Unity as it handles collisions, slopes, and steps automatically without dealing with Rigidbody physics directly.
Script: FPSController.cs
csharp
using UnityEngine;
[RequireComponent(typeof(CharacterController))] // Ensures the GameObject has a CharacterController
public class FPSController : MonoBehaviour
{
[Header("Player Movement")]
[SerializeField] private float walkingSpeed = 5f;
[SerializeField] private float runningSpeed = 8f;
[SerializeField] private float jumpHeight = 2f;
[SerializeField] private float gravity = -9.81f; // Standard gravity value
[Header("Mouse Look")]
[SerializeField] private float mouseSensitivity = 100f;
[SerializeField] private Transform playerCamera; // Assign your player camera here
[SerializeField] private float minPitch = -90f; // Limit looking down
[SerializeField] private float maxPitch = 90f; // Limit looking up
private CharacterController controller;
private Vector3 velocity; // Stores player's current velocity (mainly for gravity/jump)
private float cameraPitch = 0f; // Stores current vertical camera rotation
private bool isRunning;
void Awake()
{
controller = GetComponent<CharacterController>();
// Ensure playerCamera is assigned, try to find main camera child if not
if (playerCamera == null)
{
playerCamera = Camera.main?.transform; // Get main camera if it exists
if (playerCamera != null && playerCamera.parent != transform)
{
// If the main camera is found but not a child, warn and try to find child
Debug.LogWarning("FPSController: Player Camera not assigned. Found Main Camera, but it's not a child. Trying to find Camera child.");
playerCamera = transform.GetComponentInChildren<Camera>()?.transform;
}
if (playerCamera == null)
{
Debug.LogError("FPSController: Player Camera is not assigned and no Camera component found as a child or main camera. Mouse look will not work.");
}
}
// Lock and hide cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
HandleMovementInput();
ApplyGravityAndJump();
HandleMouseLook();
// Unlock cursor on Escape key
if (Input.GetKeyDown(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
private void HandleMovementInput()
{
// Get input axes (W/S, A/D or Arrow Keys)
float moveHorizontal = Input.GetAxisRaw("Horizontal");
float moveVertical = Input.GetAxisRaw("Vertical");
// Check if running
isRunning = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
float currentSpeed = isRunning ? runningSpeed : walkingSpeed;
// Calculate movement direction relative to the player's facing direction
Vector3 moveDirection = transform.right * moveHorizontal + transform.forward * moveVertical;
// Apply speed
// Normalize to prevent faster diagonal movement, but only if there's input
if (moveDirection.magnitude > 1)
{
moveDirection.Normalize();
}
// Move the character controller
// We apply the calculated horizontal movement here. Vertical movement (gravity/jump)
// is handled in ApplyGravityAndJump.
controller.Move(moveDirection * currentSpeed * Time.deltaTime);
}
private void ApplyGravityAndJump()
{
// Check if grounded and reset vertical velocity
if (controller.isGrounded && velocity.y < 0)
{
// A small negative number ensures the player stays grounded
// and the check controller.isGrounded works correctly.
velocity.y = -2f;
}
// Handle Jump Input
// Check if grounded before allowing a jump
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
// Calculate the initial vertical velocity required to reach jumpHeight
// Formula: v^2 = u^2 + 2as
// We want to find u (initial velocity) when v (final velocity at peak) is 0,
// a is gravity, and s is jumpHeight.
// 0 = u^2 + 2 * gravity * jumpHeight
// u^2 = -2 * gravity * jumpHeight
// u = sqrt(-2 * gravity * jumpHeight)
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// Apply Gravity
velocity.y += gravity * Time.deltaTime;
// Apply the vertical velocity (gravity and jump) to the character controller
// We only apply the Y component of velocity here, as X and Z are handled by horizontal movement.
controller.Move(new Vector3(0, velocity.y, 0) * Time.deltaTime);
}
private void HandleMouseLook()
{
if (playerCamera == null) return; // Don't try to look if camera isn't assigned
// Get mouse input axes
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// Rotate the player (horizontal rotation)
transform.Rotate(Vector3.up * mouseX);
// Rotate the camera (vertical rotation)
// Accumulate vertical rotation and clamp it
cameraPitch -= mouseY;
cameraPitch = Mathf.Clamp(cameraPitch, minPitch, maxPitch);
// Apply the vertical rotation to the camera's local rotation
playerCamera.localRotation = Quaternion.Euler(cameraPitch, 0f, 0f);
}
// You can call this publicly if you need to reset or change player position externally
public void ResetPosition(Vector3 newPosition)
{
controller.enabled = false; // Disable controller temporarily
transform.position = newPosition;
controller.enabled = true; // Re-enable controller
}
}
How to Use:
Create a Player GameObject: In your Unity scene, create an empty GameObject (e.g., "Player").
Add a CharacterController: Select the "Player" GameObject and click "Add Component". Search for and add Character Controller. You'll see a green outline gizmo in the scene view showing its bounds. Adjust the Height and Radius in the Inspector if needed (default Capsule shape is usually fine).
Add the Script: Add the FPSController.cs script to the "Player" GameObject.
Create/Assign a Camera:
Right-click on the "Player" GameObject in the Hierarchy.
Select "Camera". This will create a Camera as a child of the Player.
Position the camera inside the Capsule gizmo of the Character Controller, roughly where eyes would be (e.g., Y position around 1.6 for a default height of 2).
In the Inspector for the "Player" GameObject, drag the newly created "Camera" GameObject from the Hierarchy onto the Player Camera field in the FPS Controller (Script) component.
Set Up Environment: Add some ground (e.g., a large Cube) and maybe some obstacles (more Cubes) so you can test movement and collisions. Ensure the ground and obstacles have Colliders.
Default Input Setup: Unity's default Input Manager already has "Horizontal", "Vertical", "Mouse X", "Mouse Y", and "Jump" set up, so the script will work out-of-the-box with WASD/Arrow Keys, Spacebar, and Mouse movement.
Adjust Parameters: Select the "Player" GameObject and adjust Walking Speed, Running Speed, Jump Height, Gravity, Mouse Sensitivity, etc., in the Inspector to your liking.
Play: Run the scene! You should now have basic FPS movement and mouse look.
Explanation:
[RequireComponent(typeof(CharacterController))]: This attribute ensures that if you add this script to a GameObject, a CharacterController component is automatically added (or verified if it exists).
Variables: Public or [SerializeField] variables allow you to tweak parameters directly in the Unity Inspector without changing the code.
Awake(): Called when the script instance is being loaded. Used here to get a reference to the CharacterController component and handle cursor locking/hiding.
Update(): Called once per frame. This is where we handle input, calculate movement, and apply rotation.
HandleMovementInput():
Gets input from the "Horizontal" and "Vertical" axes. GetAxisRaw gives -1, 0, or 1 immediately, which is often preferred for crisp character movement. GetAxis provides smoothing.
Calculates the moveDirection based on the player's current facing direction (transform.right and transform.forward).
Normalizes the direction if the diagonal input has a magnitude greater than 1, preventing faster diagonal movement.
Selects walkingSpeed or runningSpeed based on the Left/Right Shift key.
Calls controller.Move(). CharacterController.Move takes a displacement vector (distance to move in this frame), hence multiplied by Time.deltaTime.
ApplyGravityAndJump():
Checks if the CharacterController is currently touching the ground (controller.isGrounded).
If grounded and falling (velocity.y < 0), it resets velocity.y to a small negative value, effectively sticking it to the ground.
Checks for the "Jump" input (Input.GetButtonDown). GetButtonDown is true only in the frame the button is pressed.
If jumping and grounded, calculates the initial upward velocity.y needed to reach the desired jumpHeight using basic physics.
Applies gravity by adding gravity * Time.deltaTime to the velocity.y each frame.
Calls controller.Move(new Vector3(0, velocity.y, 0) * Time.deltaTime) to apply the vertical movement caused by gravity and jumping. We create a here because the horizontal movement was handled in , and adds the displacement vectors together.
new Vector3
HandleMovementInput
controller.Move
HandleMouseLook():
Gets input from "Mouse X" and "Mouse Y".
Rotates the player object (transform) around the Y-axis (Vector3.up) based on Mouse X input. This turns the whole character horizontally.
Rotates the camera object (playerCamera) around its local X-axis (vertical rotation). We store and clamp the cameraPitch variable to prevent looking straight up/down from flipping the view. localRotation is used because it's a child object.
Time.deltaTime: Crucial for frame-rate independence. Multiplies movement and rotation values to ensure they happen at a consistent speed regardless of how fast or slow your game is running.
Cursor Locking: Hides the mouse cursor and locks it to the center of the screen, essential for most FPS games. Allows unlocking with Escape.