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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Player Sphere
// The sphere that the player can control and move around
public class MovingSphere : MonoBehaviour
{
// if we want input relative to a
// camera(or some other arbitrary object) we
// put that object here
[SerializeField]
Transform playerInputSpace = default;
[SerializeField]
Transform ball = default;
// "self" objects
Rigidbody body;
Renderer renderer;
[SerializeField, Range(0f, 100f)]
float maxSpeed = 10f;
[SerializeField, Range(0f, 100f)]
float maxAcceleration = 10f;
[SerializeField, Range(0f, 100f)]
float maxAirAcceleration = 1f;
Vector3 velocity;
[SerializeField, Range(0f, 10f)]
float jumpHeight = 2f;
[SerializeField, Range(0, 5)]
int maxAirJumps;
bool desiredJump;
int jumpPhase;
// dont snap to surface if going too fast
[SerializeField, Range(0f, 100f)]
float maxSnapSpeed = 100f;
[SerializeField, Min(0f)]
float raycastProbeDistance = 1f;
// Define the following 2 variables in the editor
[SerializeField]
LayerMask probeMask = -1;
[SerializeField]
LayerMask stairsMask = -1;
int stepsSinceLastGrounded;
int stepsSinceLastJump;
Vector3 contactNormal;
Vector3 steepNormal;
int groundContactCount;
int steepContactCount;
bool OnGround => groundContactCount > 0;
bool OnSteep => steepContactCount > 0;
Vector3 upAxis;
Vector3 rightAxis;
Vector3 forwardAxis;
// 1.0 means walls
// 0.0 means floors
[SerializeField, Range(0f, 1f)]
float maxSlopeAngle = 0.44f;
float minGroundDotProduct;
[SerializeField, Range(0f, 1f)]
float maxStairAngle = 0.6f;
float minStairsDotProduct;
[SerializeField, Min(0f)]
float ballAlignSpeed = 180f;
[SerializeField, Min(0.1f)]
float ballRadius = 0.5f;
Vector3 lastContactNormal;
Vector3 inputVelocity;
void Awake()
{
body = GetComponent<Rigidbody>();
renderer = ball.GetComponent<Renderer>();
// we define our own gravity so disable the built in one.
body.useGravity = false;
}
void Update()
{
// --- Get Input ---
Vector2 playerInput = new Vector2(
Input.GetAxis("Horizontal"),
Input.GetAxis("Vertical")
);
playerInput = Vector2.ClampMagnitude(playerInput, 1f);
desiredJump |= Input.GetButtonDown("Jump");
// --- ---
// --- Calculate what is considered the "floor" ---
if(playerInputSpace)
{
rightAxis = ProjectDirectionOnPlane(playerInputSpace.right, upAxis);
forwardAxis = ProjectDirectionOnPlane(playerInputSpace.forward, upAxis);
}
else
{
rightAxis = ProjectDirectionOnPlane(Vector3.right, upAxis);
forwardAxis = ProjectDirectionOnPlane(Vector3.forward, upAxis);
}
inputVelocity = new Vector3(playerInput.x, 0f, playerInput.y) * maxSpeed;
// --- ---
// Update visual orientation of the ball
UpdateBall();
}
void FixedUpdate()
{
Vector3 gravity = CustomGravity.GetGravity(body.position, out upAxis);
UpdateState();
// apply input velocities
AdjustVelocity();
if(desiredJump)
{
desiredJump = false;
Jump(gravity);
}
velocity += gravity * Time.deltaTime;
body.velocity = velocity;
ClearState();
}
void ClearState() {
lastContactNormal = contactNormal;
groundContactCount = steepContactCount = 0;
contactNormal = steepNormal = Vector3.zero;
}
void UpdateState()
{
// if slope angle changed in editor, update these
minGroundDotProduct = Mathf.Cos(maxSlopeAngle * 90 * Mathf.Deg2Rad);
minStairsDotProduct = Mathf.Cos(maxStairAngle * 90 * Mathf.Deg2Rad);
stepsSinceLastGrounded += 1;
stepsSinceLastJump += 1;
velocity = body.velocity;
if(OnGround || SnapToGround() || CheckSteepContacts())
{
stepsSinceLastGrounded = 0;
if(stepsSinceLastJump > 1)
jumpPhase = 0;
if(groundContactCount > 1)
contactNormal.Normalize();
}
else
contactNormal = upAxis;
}
// Update visual orientation of the ball
void UpdateBall()
{
Vector3 movement = body.velocity * Time.deltaTime;
float distance = movement.magnitude;
if(distance < 0.001f)
return;
float angle = distance * (180f / Mathf.PI) / ballRadius;
Vector3 rotationAxis =
Vector3.Cross(lastContactNormal, movement).normalized;
Quaternion rotation =
Quaternion.Euler(rotationAxis * angle) * ball.localRotation;
if(ballAlignSpeed > 0f)
rotation = AlignBallRotation(rotationAxis, rotation, distance);
ball.localRotation = rotation;
}
Quaternion AlignBallRotation(Vector3 rotationAxis, Quaternion rotation, float traveledDistance)
{
Vector3 ballAxis = ball.up;
float dot = Mathf.Clamp(Vector3.Dot(ballAxis, rotationAxis), -1f, 1f);
float angle = Mathf.Acos(dot) * Mathf.Rad2Deg;
float maxAngle = ballAlignSpeed * traveledDistance;
Quaternion newAlignment =
Quaternion.FromToRotation(ballAxis, rotationAxis) * rotation;
if(angle <= maxAngle)
return newAlignment;
else
return Quaternion.SlerpUnclamped(
rotation,
newAlignment,
maxAngle / angle
);
}
void Jump(Vector3 gravity)
{
Vector3 jumpDirection;
if(OnGround)
jumpDirection = contactNormal;
else if(OnSteep)
{
jumpDirection = steepNormal;
jumpPhase = 0;
}
else if((maxAirJumps > 0) && (jumpPhase <= maxAirJumps))
{
if(jumpPhase == 0)
jumpPhase = 1;
jumpDirection = contactNormal;
}
else
return;
stepsSinceLastJump = 0;
jumpPhase += 1;
float jumpSpeed = Mathf.Sqrt(2f * gravity.magnitude * jumpHeight);
jumpDirection = (jumpDirection + upAxis).normalized;
float alignedSpeed = Vector3.Dot(velocity, jumpDirection);
if(alignedSpeed > 0f)
jumpSpeed = Mathf.Max(jumpSpeed - alignedSpeed, 0f);
velocity += jumpDirection * jumpSpeed;
}
bool SnapToGround()
{
if(stepsSinceLastGrounded > 1 || stepsSinceLastJump <= 2)
return false;
float speed = velocity.magnitude;
if(speed > maxSnapSpeed)
return false;
if(!Physics.Raycast(
body.position,
-upAxis,
out RaycastHit hit,
raycastProbeDistance,
probeMask
))
return false;
float upDot = Vector3.Dot(upAxis, hit.normal);
if(upDot < GetMinDot(hit.collider.gameObject.layer))
return false;
Debug.Log(Time.time);
groundContactCount = 1;
contactNormal = hit.normal;
float dot = Vector3.Dot(velocity, hit.normal);
if(dot > 0f)
velocity = (velocity - hit.normal * dot).normalized * speed;
return true;
}
// --- Hooks into Unity api for collisions ---
void OnCollisionStay(Collision collision) {
EvaluateCollision(collision);
}
void OnCollisionEnter(Collision collision) {
EvaluateCollision(collision);
}
// --- ---
void EvaluateCollision(Collision collision) {
float minDot = GetMinDot(collision.gameObject.layer);
for(int i = 0; i < collision.contactCount; i++)
{
Vector3 normal = collision.GetContact(i).normal;
float upDot = GetMinDot(collision.gameObject.layer);
if(upDot >= minDot)
{
groundContactCount += 1;
contactNormal += normal;
}
else if(upDot > -0.01f)
{
steepContactCount += 1;
steepNormal += normal;
}
}
}
void AdjustVelocity()
{
Vector3 xAxis = ProjectDirectionOnPlane(rightAxis, contactNormal);
Vector3 zAxis = ProjectDirectionOnPlane(forwardAxis, contactNormal);
Vector3 currentVel = new Vector3(
Vector3.Dot(velocity, xAxis),
0f,
Vector3.Dot(velocity, zAxis)
);
float maxSpeedChange = Time.deltaTime;
if(OnGround)
maxSpeedChange *= maxAcceleration;
else
maxSpeedChange *= maxAirAcceleration;
Vector3 newVel = new Vector3(
Mathf.MoveTowards(currentVel.x, inputVelocity.x, maxSpeedChange),
0f,
Mathf.MoveTowards(currentVel.z, inputVelocity.z, maxSpeedChange)
);
velocity += xAxis * (newVel.x - currentVel.x) + zAxis * (newVel.z - currentVel.z);
}
Vector3 ProjectDirectionOnPlane(Vector3 direction, Vector3 normal)
{
return (direction - normal * Vector3.Dot(direction, normal)).normalized;
}
float GetMinDot(int layer)
{
if ((stairsMask & (1 << layer)) > 0)
return minStairsDotProduct;
else
return minGroundDotProduct;
}
bool CheckSteepContacts()
{
// check if there are multiple contact points
// if there are: use the average normal of
// all contacts instead
if(steepContactCount > 1)
{
steepNormal.Normalize();
float upDot = Vector3.Dot(upAxis, steepNormal);
if(upDot >= minGroundDotProduct)
{
groundContactCount = 1;
contactNormal = steepNormal;
return true;
}
}
return false;
}
}
|