-
Notifications
You must be signed in to change notification settings - Fork 53
/
FirstPersonController.cs
71 lines (57 loc) · 1.85 KB
/
FirstPersonController.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
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (GravityBody))]
public class FirstPersonController : MonoBehaviour {
// public vars
public float mouseSensitivityX = 1;
public float mouseSensitivityY = 1;
public float walkSpeed = 6;
public float jumpForce = 220;
public LayerMask groundedMask;
// System vars
bool grounded;
Vector3 moveAmount;
Vector3 smoothMoveVelocity;
float verticalLookRotation;
Transform cameraTransform;
Rigidbody rigidbody;
void Awake() {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
cameraTransform = Camera.main.transform;
rigidbody = GetComponent<Rigidbody> ();
}
void Update() {
// Look rotation:
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * mouseSensitivityX);
verticalLookRotation += Input.GetAxis("Mouse Y") * mouseSensitivityY;
verticalLookRotation = Mathf.Clamp(verticalLookRotation,-60,60);
cameraTransform.localEulerAngles = Vector3.left * verticalLookRotation;
// Calculate movement:
float inputX = Input.GetAxisRaw("Horizontal");
float inputY = Input.GetAxisRaw("Vertical");
Vector3 moveDir = new Vector3(inputX,0, inputY).normalized;
Vector3 targetMoveAmount = moveDir * walkSpeed;
moveAmount = Vector3.SmoothDamp(moveAmount,targetMoveAmount,ref smoothMoveVelocity,.15f);
// Jump
if (Input.GetButtonDown("Jump")) {
if (grounded) {
rigidbody.AddForce(transform.up * jumpForce);
}
}
// Grounded check
Ray ray = new Ray(transform.position, -transform.up);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1 + .1f, groundedMask)) {
grounded = true;
}
else {
grounded = false;
}
}
void FixedUpdate() {
// Apply movement to rigidbody
Vector3 localMove = transform.TransformDirection(moveAmount) * Time.fixedDeltaTime;
rigidbody.MovePosition(rigidbody.position + localMove);
}
}