Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Write me a unity code for FPS player controll

  1. User

    Write me a unity code for FPS player controll

  2. Assistant

    Sure, here's a basic example of FPS player control script in Unity:

    using UnityEngine;
    
    public class PlayerController : MonoBehaviour
    {
        public float moveSpeed = 5f;
        public float mouseSensitivity = 3f;
        
        private float verticalRotation = 0f;
        private CharacterController characterController;
        
        void Start()
        {
            characterController = GetComponent<CharacterController>();
            Cursor.lockState = CursorLockMode.Locked; // Hide cursor
        }
    
        void Update()
        {
            // Player movement
            float vertical = Input.GetAxis("Vertical") * moveSpeed;
            float horizontal = Input.GetAxis("Horizontal") * moveSpeed;
            
            Vector3 movement = new Vector3(horizontal, 0, vertical);
            movement = transform.rotation * movement;
            characterController.SimpleMove(movement);
            
            // Player look rotation
            float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
            float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
            
            verticalRotation -= mouseY;
            verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
            
            transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
            transform.parent.Rotate(Vector3.up * mouseX);
            
            // Unlock cursor on pressing Escape key
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                Cursor.lockState = CursorLockMode.None;
            }
        }
    }
    

    Make sure to attach this script to the player character in your Unity scene. It allows the player to move using input from the "Vertical" and "Horizontal" axes, and look around using mouse input. The movement is controlled using CharacterController.SimpleMove() to handle physics interactions correctly. Feel free to modify the variables moveSpeed and mouseSensitivity to your desired values.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.