0% found this document useful (0 votes)
18 views4 pages

Fps Contoller For Unity

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Fps Contoller For Unity

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

using System.

Collections;

using System.Collections.Generic;

using UnityEngine;

[RequireComponent(typeof(CharacterController))]

public class FpsController : MonoBehaviour

public Camera playerCamera;

public float walkSpeed = 6f;

public float runSpeed = 12f;

public float jumpPower = 7f;

public float gravity = 10f;

public float lookSpeed = 2f;

public float lookXLimit = 45f;

Vector3 moveDirection = Vector3.zero;

float rotationX = 0;

public bool canMove = true;

CharacterController characterController;
// Start is called before the first frame update

void Start()

characterController = GetComponent<CharacterController>();

Cursor.lockState = CursorLockMode.Locked;

Cursor.visible = false;

// Update is called once per frame

void Update()

#region Handles Movment

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 ? runSpeed : walkSpeed) *


Input.GetAxis("Vertical") : 0;

float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) *


Input.GetAxis("Horizontal") : 0;

float movementDirectionY = moveDirection.y;

moveDirection = (forward * curSpeedX) + (right * curSpeedY);

#endregion
#region Handles Jumping

if (Input.GetButton("Jump") && canMove &&


characterController.isGrounded)

moveDirection.y = jumpPower;

else

moveDirection.y = movementDirectionY;

if (!characterController.isGrounded)

moveDirection.y -= gravity * Time.deltaTime;

#endregion

#region Handles Rotation

characterController.Move(moveDirection * Time.deltaTime);

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);

#endregion

You might also like