-
Notifications
You must be signed in to change notification settings - Fork 2
/
First_Person_Movement.cs
89 lines (77 loc) · 2.46 KB
/
First_Person_Movement.cs
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
81
82
83
84
85
86
87
88
89
using UnityEngine;
public class First_Person_Movement : MonoBehaviour
{
private Vector3 Velocity;
private Vector3 PlayerMovementInput;
private Vector2 PlayerMouseInput;
private bool Sneaking = false;
private float xRotation;
[Header("Components Needed")]
[SerializeField] private Transform PlayerCamera;
[SerializeField] private CharacterController Controller;
[SerializeField] private Transform Player;
[Space]
[Header("Movement")]
[SerializeField] private float Speed;
[SerializeField] private float JumpForce;
[SerializeField] private float Sensetivity;
[SerializeField] private float Gravity = 9.81f;
[Space]
[Header("Sneaking")]
[SerializeField] private bool Sneak = false;
[SerializeField] private float SneakSpeed;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
PlayerMouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
MovePlayer();
MoveCamera();
if (Input.GetKey(KeyCode.RightShift) && Sneak)
{
Player.localScale = new Vector3(1f, 0.5f, 1f);
Sneaking = true;
}
if (Input.GetKeyUp(KeyCode.RightShift))
{
Player.localScale = new Vector3(1f, 1f, 1f);
Sneaking = false;
}
}
private void MovePlayer()
{
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput);
if (Controller.isGrounded)
{
Velocity.y = -1f;
if (Input.GetKeyDown(KeyCode.Space) && Sneaking == false)
{
Velocity.y = JumpForce;
}
}
else
{
Velocity.y += Gravity * -2f * Time.deltaTime;
}
if (Sneaking)
{
Controller.Move(MoveVector * SneakSpeed * Time.deltaTime);
}
else
{
Controller.Move(MoveVector * Speed * Time.deltaTime);
}
Controller.Move(Velocity * Time.deltaTime);
}
private void MoveCamera()
{
xRotation -= PlayerMouseInput.y * Sensetivity;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.Rotate(0f, PlayerMouseInput.x * Sensetivity, 0f);
PlayerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
}