-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerMovement.cs
More file actions
108 lines (78 loc) · 2.69 KB
/
PlayerMovement.cs
File metadata and controls
108 lines (78 loc) · 2.69 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
private CharacterController controller;
private Animator anim;
private void Start() {
controller = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>();
}
private void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.Mouse0))
{
StartCoroutine(Attack());
}
}
private void Move() {
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);
if (isGrounded) {
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift)) {
Run();
} else if (moveDirection == Vector3.zero) {
Idle();
}
moveDirection *= moveSpeed;
controller.Move(moveDirection * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space)) {
Jump();
}
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle() {
anim.SetFloat("Speed", 0, 0.1f, Time.deltaTime);
}
private void Walk() {
moveSpeed = walkSpeed;
anim.SetFloat("Speed", 0.5f, 0.1f, Time.deltaTime);
}
private void Run() {
moveSpeed = runSpeed;
anim.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
private void Jump() {
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
private IEnumerator Attack() {
//Temporary fix.
anim.SetLayerWeight(anim.GetLayerIndex("Attack Layer"), 1);
anim.SetTrigger("Attack");
yield return new WaitForSeconds(1);
anim.SetLayerWeight(anim.GetLayerIndex("Attack Layer"), 0);
}
}