This example script allow us to control movement and rotation of camera in first person perspective. Example code is given below:
"moveSpeed" is a public variable which control movement speed of our camera and "mouseSensitivity" variable control sensitivity of mouse look.
"rotationX" and "rotationY" are private variables which are used for storing current rotation of camera.
"Start()" function will lock our cursor so player is unable to move it outside of game window.
"Update()" function will use Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") method for getting input for movement of camera so we can move our camera left, right, forward, and backward by horizontal and vertical keys like WASD or arrow.
Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y") for getting input for rotation of camera.
We used "Mathf.Clamp()" function in this script for limiting rotationX between a certain range so this will prevent our camera from rotating upside down.
We used Time.deltaTime to multiply movement so this will make camera movement smooth regardless of frame rate.
Add this script to Main Camera in your scene for enabling simple first-person camera movement. You can tweak moveSpeed and mouseSensitivity variables as per your requirement.
Comments
Post a Comment