-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCharacterMovement.cs
118 lines (93 loc) · 2.59 KB
/
CharacterMovement.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using UnityEngine;
using System.Collections;
public class CharacterMovement : MonoBehaviour {
float moveSpeedMultiplier = 1;
float stationaryTurnSpeed = 180;
float movingTurnSpeed = 360;
bool onGround;
Animator animator;
Vector3 moveInput;
float turnAmount;
float forwardAmount;
Vector3 velocity;
Rigidbody rigidbody;
float jumpPower = 10;
IComparer rayHitComparer;
// Use this for initialization
void Start () {
rigidbody = GetComponent<Rigidbody> ();
SetupAnimator ();
}
public void Move(Vector3 move){
if (move.magnitude > 1) {
move.Normalize ();
}
this.moveInput = move;
velocity = rigidbody.velocity;
ConvertMoveInput ();
ApplyExtraTurnRotation ();
GroundCheck ();
UpdateAnimator ();
}
void SetupAnimator(){
animator = GetComponent<Animator> ();
foreach (Animator childAnimator in GetComponentsInChildren<Animator>()) {
if (childAnimator != animator) {
animator.avatar = childAnimator.avatar;
Destroy (childAnimator);
break;
}
}
}
void OnAnimatorMove(){
if (onGround && Time.deltaTime > 0) {
Vector3 v = (animator.deltaPosition * moveSpeedMultiplier) / Time.deltaTime;
v.y = rigidbody.velocity.y;
rigidbody.velocity = v;
}
}
// Update is called once per frame
void Update () {
}
void GroundCheck(){
Ray ray = new Ray (transform.position + Vector3.up * 0.1f, -Vector3.up);
RaycastHit[] hits = Physics.RaycastAll (ray, 0.5f);
rayHitComparer = new RayHitComparer ();
System.Array.Sort (hits, rayHitComparer);
if (velocity.y < jumpPower * .5f) {
//onGround = false;
rigidbody.useGravity = true;
foreach (var hit in hits) {
if (!hit.collider.isTrigger) {
if (velocity.y <= 0) {
rigidbody.position = Vector3.MoveTowards (rigidbody.position, hit.point, Time.deltaTime * 5);
}
onGround = true;
rigidbody.useGravity = false;
//
break;
}
}
}
}
void ConvertMoveInput(){
Vector3 localMove = transform.InverseTransformDirection (moveInput);
turnAmount = Mathf.Atan2 (localMove.x, localMove.z);
forwardAmount = localMove.z;
}
void UpdateAnimator(){
animator.applyRootMotion = true;
animator.SetFloat ("Forward", forwardAmount, 0.1f, Time.deltaTime);
animator.SetFloat ("Turn", turnAmount, 0.1f, Time.deltaTime);
}
void ApplyExtraTurnRotation(){
float turnSpeed = Mathf.Lerp (stationaryTurnSpeed, movingTurnSpeed, forwardAmount);
transform.Rotate (0, turnAmount * turnSpeed * Time.deltaTime, 0);
}
class RayHitComparer : IComparer
{
public int Compare(object x, object y){
return ((RaycastHit)x).distance.CompareTo(((RaycastHit)y).distance);
}
}
}