Skip to content

Instantly share code, notes, and snippets.

@dmattox10
Created June 14, 2025 22:36
Show Gist options
  • Select an option

  • Save dmattox10/b6153c8938cb27f74fbe3b98c7a6b785 to your computer and use it in GitHub Desktop.

Select an option

Save dmattox10/b6153c8938cb27f74fbe3b98c7a6b785 to your computer and use it in GitHub Desktop.

Revisions

  1. dmattox10 created this gist Jun 14, 2025.
    64 changes: 64 additions & 0 deletions FlyCamera.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    using UnityEngine;

    public class FlyCamera : MonoBehaviour
    {
    public float moveSpeed = 10f;
    public float mouseSensitivity = 2f;
    public float speedMultiplier = 2f;

    private float rotationX = 0.0f;
    private float rotationY = 0.0f;

    void Start()
    {
    // Lock and hide the cursor
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
    }

    void Update()
    {
    // Mouse look
    rotationX -= Input.GetAxis("Mouse Y") * mouseSensitivity;
    rotationY += Input.GetAxis("Mouse X") * mouseSensitivity;

    rotationX = Mathf.Clamp(rotationX, -90f, 90f);

    transform.rotation = Quaternion.Euler(rotationX, rotationY, 0);

    // Movement
    float currentSpeed = moveSpeed;
    if (Input.GetKey(KeyCode.LeftShift))
    {
    currentSpeed *= speedMultiplier;
    }

    Vector3 movement = Vector3.zero;

    // WASD movement
    if (Input.GetKey(KeyCode.W))
    movement += transform.forward;
    if (Input.GetKey(KeyCode.S))
    movement -= transform.forward;
    if (Input.GetKey(KeyCode.A))
    movement -= transform.right;
    if (Input.GetKey(KeyCode.D))
    movement += transform.right;

    // Up/Down movement
    if (Input.GetKey(KeyCode.Space))
    movement += Vector3.up;
    if (Input.GetKey(KeyCode.LeftControl))
    movement -= Vector3.up;

    transform.position += movement * currentSpeed * Time.deltaTime;

    // Press Escape to toggle cursor lock
    if (Input.GetKeyDown(KeyCode.Escape))
    {
    Cursor.lockState = Cursor.lockState == CursorLockMode.Locked ?
    CursorLockMode.None : CursorLockMode.Locked;
    Cursor.visible = !Cursor.visible;
    }
    }
    }