unity c# fps controller code example

Example 1: unity simple fps controller

//Simple 3D FPS controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]

public class SC_FPSController : MonoBehaviour
{
    public float walkingSpeed = 7.5f;
    public float runningSpeed = 11.5f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Camera playerCamera;
    public float lookSpeed = 2.0f;
    public float lookXLimit = 45.0f;

    CharacterController characterController;
    Vector3 moveDirection = Vector3.zero;
    float rotationX = 0;

    [HideInInspector]
    public bool canMove = true;

    void Start()
    {
        characterController = GetComponent<CharacterController>();

        // Lock cursor
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    void Update()
    {
        // We are grounded, so recalculate move direction based on axes
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 right = transform.TransformDirection(Vector3.right);
        // Press Left Shift to run
        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
        float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
        float movementDirectionY = moveDirection.y;
        moveDirection = (forward * curSpeedX) + (right * curSpeedY);

        if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
        {
            moveDirection.y = jumpSpeed;
        }
        else
        {
            moveDirection.y = movementDirectionY;
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        if (!characterController.isGrounded)
        {
            moveDirection.y -= gravity * Time.deltaTime;
        }

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        // Player and Camera rotation
        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
            transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
        }
    }
}

Example 2: fps controller c#

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
    [SerializeField] float speed = 3f;
    [SerializeField] float sensitivity = 150f;
    [SerializeField] float jumpHeight = 4f;
    [Space]
    [SerializeField] Camera cam = null;
    [SerializeField] Rigidbody rb;
    float clampedXRot;
    bool onGround = true;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Movement()
    {
        float _xMove = Input.GetAxis("Horizontal"); // Defines Input Axes
        float _zMove = Input.GetAxis("Vertical");
        float _xRot = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
        float _yRot = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;

        Vector3 movVert = _zMove * transform.forward;
        Vector3 movHor = _xMove * transform.right;

        Vector3 velocity = (movHor + movVert) * speed * Time.deltaTime;
        Vector3 rotation = new Vector3(0f, _yRot, 0f);

        clampedXRot += _xRot;
        clampedXRot = Mathf.Clamp(clampedXRot, -90f, 90f);

        transform.Rotate(rotation);
        rb.MovePosition(rb.position + velocity);
        cam.transform.localRotation = Quaternion.Euler(clampedXRot, 0f, 0f); // Parent the camera to the player and reset the transform
    }

    void Jump()
    {
        if (Input.GetButton("Jump"))
        {
            if (onGround == true)
            {
                rb.velocity = new Vector3(0f, jumpHeight, 0f);
                onGround = false;
            }
        }
    }

    void FixedUpdate()
    {
        if (transform != null)
        {
            Movement();
            Jump();
        }
    }

    private void OnCollisionEnter(Collision collision) // Give the ground the tag "Ground"
    {
        if (collision.collider.tag == "Ground")
        {
            onGround = true;
        }
    }
}