-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicController.cs
More file actions
89 lines (76 loc) · 2.61 KB
/
Copy pathBasicController.cs
File metadata and controls
89 lines (76 loc) · 2.61 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
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class BasicController : MonoBehaviour
{
[SerializeField] private float maxSpeed = 8.0f;
[SerializeField] private float acceleration = 12.0f;
[SerializeField] private float gravity = 9.81f;
[SerializeField] private float jumpForce = 5.0f;
[SerializeField] private Camera fpsCam;
[SerializeField] private float lookSpeed = 5.0f;
private Rigidbody rb;
private Vector3 inputDir;
private Vector3 FlatVelocity => new Vector3(rb.velocity.x, 0, rb.velocity.z);
private void Awake()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
rb.interpolation = RigidbodyInterpolation.Interpolate;
rb.useGravity = false;
}
float xRot, yRot;
private void Update()
{
inputDir.x = Input.GetAxisRaw("Horizontal");
inputDir.z = Input.GetAxisRaw("Vertical");
inputDir.Normalize();
// Camera Look
Vector2 mouseDelta;
mouseDelta.x = Input.GetAxisRaw("Mouse X");
mouseDelta.y = -Input.GetAxisRaw("Mouse Y");
xRot += lookSpeed * mouseDelta.y;
yRot += lookSpeed * mouseDelta.x;
xRot = Mathf.Clamp(xRot, -90, 90);
fpsCam.transform.rotation = Quaternion.Euler(xRot, yRot, 0);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private void FixedUpdate()
{
rb.AddForce(Vector3.down * Mathf.Abs(gravity));
Vector3 moveDirDesired = Quaternion.Euler(0, fpsCam.transform.eulerAngles.y, 0) * inputDir;
moveDirDesired.Normalize();
if (isGrounded)
{
Vector3 force = moveDirDesired * acceleration - acceleration / maxSpeed * FlatVelocity;
rb.AddForce(force);
}
else
{
Vector3 airForce = moveDirDesired * maxSpeed - Vector3.ClampMagnitude(FlatVelocity, maxSpeed);
rb.AddForce(airForce);
}
}
private bool isGrounded, groundDetectedThisFrame;
private void OnCollisionStay(Collision collision)
{
for (int i = 0; i < collision.contactCount; i++)
{
// ideally we should use slope angular limit here
if (Vector3.Dot(Vector3.up, collision.contacts[i].normal) > 0.5f)
{
isGrounded = true;
groundDetectedThisFrame = true;
break;
}
}
}
private void LateUpdate()
{
if (!groundDetectedThisFrame)
isGrounded = false;
groundDetectedThisFrame = false;
}
}