-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfpsController.cs
More file actions
80 lines (56 loc) · 2.24 KB
/
fpsController.cs
File metadata and controls
80 lines (56 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class FPScontroller : MonoBehaviour
{
[SerializeField] private Camera playerCamera;
[Header("Speed")]
[SerializeField] float walkSpeed = 5f;
[SerializeField] float runSpeed = 10f;
[Header("Vertical components")]
[SerializeField] float jumpPower = 6f;
[SerializeField] float gravity = 10f;
[Header("Mouse sensitivity & look limit")]
[SerializeField] private float lookSpeed = 2f;
[SerializeField] private float lookXlimit = 45f;
private Vector3 moveDirection = Vector3.zero;
private float rotationX = 0;
private bool canMove = true;
private CharacterController characterController;
void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
// 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);
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpPower;
}
else
{
moveDirection.y = movementDirectionY;
}
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
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);
}
}
}