PlayerActor.cs 12.9 KB
Newer Older
1
2
3
using System;
using System.Collections;
using System.Collections.Generic;
4
using System.Linq;
5
using UnityEngine;
Markus Schlösser's avatar
Markus Schlösser committed
6
using UnityEngine.EventSystems;
7
using UnityEngine.Tilemaps;
Christopher Benes's avatar
Christopher Benes committed
8
using NaughtyAttributes;
9

10
public class PlayerActor : MonoBehaviour, IResetable {
11
12
	private const int MAX_STEPS = 128;

13
14
15
16
17
18
19
20
21
	private const float CONCAVE_RADIUS = 0.5f;
	private const float CONVEX_RADIUS = 1.5f;

	private const float MOVE_ANIMATION_TIME_PER_TILE = 0.25f;
	private const float JUMP_ANIMATION_TIME_PER_TILE = 0.125f;

	private const float CONCAVE_ANIMATION_TIME = 1.0f / Mathf.PI;
	private const float CONVEX_ANIMATION_TIME = 3.0f / 16.0f * Mathf.PI;

22
	private Coroutine movementRoutine;
23

Marcel Kuehn's avatar
Marcel Kuehn committed
24
25
26
27
	private Vector3 startingPosition;

	private Orientation startingOrientation;

28
29
	public Orientation Orientation => orientation;

30
31
32
33
34
	private enum MovementDirection {
		Left = -1,
		Right = 1
	}

35
36
	[SerializeField] private GameObject trackingPoint;

Markus Schlösser's avatar
Markus Schlösser committed
37
38
	[SerializeField] private Collider2D col;

39
40
41
42
	[SerializeField] private Tilemap tilemap;

	[SerializeField] private Orientation orientation = Orientation.Up;

43
44
	[SerializeField] private MovementDirection facing = MovementDirection.Right;

Markus Schlösser's avatar
Markus Schlösser committed
45
46
47
	[SerializeField] private InputProvider inputProvider;

	[SerializeField] private Animator animator;
48

Markus Schlösser's avatar
Markus Schlösser committed
49
50
51
52
	[SerializeField] private ParticleSystem deathEffect;

	[SerializeField] private SpriteRenderer sprite;

Markus Schlösser's avatar
Markus Schlösser committed
53
54
	[SerializeField] private GameObject headlight;

Markus Schlösser's avatar
Markus Schlösser committed
55
56
	[SerializeField] private float peekingDistance;

Markus Schlösser's avatar
Markus Schlösser committed
57
58
	private readonly Collider2D[] contactBuffer = new Collider2D[64];

59
60
61
	private void Start() {
		Cinemachine.CinemachineVirtualCamera cam = Camera.main.GetComponent<Cinemachine.CinemachineVirtualCamera>();

Marcel Kuehn's avatar
Marcel Kuehn committed
62
63
		startingPosition = transform.position;
		startingOrientation = orientation;
Markus Schlösser's avatar
Markus Schlösser committed
64

65
66
67
68
69
		if (cam != null) {
			cam.Follow = trackingPoint.transform;
		}
	}

70
	private void Update() {
71
		animator.SetBool("isRunning", movementRoutine != null);
72
73
74
75
76
77
78
79
		if (inputProvider.PeekingPressed && movementRoutine == null) {
			trackingPoint.transform.localPosition = Vector3.up * peekingDistance;
			animator.SetBool("isPeeking", true);
		} else {
			trackingPoint.transform.localPosition = Vector3.zero;
			animator.SetBool("isPeeking", false);
		}

80
		if (movementRoutine != null) return;
81
82
83

		transform.position = tilemap.GetCellCenterWorld(tilemap.WorldToCell(transform.position));

Markus Schlösser's avatar
Markus Schlösser committed
84
85
86
87
88
89
		if (inputProvider.InteractionPressed) {
			int numResults = col.GetContacts(contactBuffer);

			for (int i = 0; i < numResults; ++i) {
				ExecuteEvents.ExecuteHierarchy<IInteractible>(contactBuffer[i].gameObject, null, (x, y) => x.Interact(this));
			}
90
91
		}

92
93
94
95
96
		IEnumerator movement = GetMovementOperation();
		if (movement != null) {
			movementRoutine = StartCoroutine(movement);
		} else {
			movementRoutine = null;
97
98
99
		}
	}

Markus Schlösser's avatar
Markus Schlösser committed
100
101
	private void OnTriggerEnter2D(Collider2D other) {
		// Collides with Hazard
102
		if (other.gameObject.layer == 11 || other.gameObject.layer == 13) {
Markus Schlösser's avatar
Markus Schlösser committed
103
			StartCoroutine(Die());
Markus Schlösser's avatar
Markus Schlösser committed
104
105
106
		}
	}

Christopher Benes's avatar
Christopher Benes committed
107
    [Button]
Markus Schlösser's avatar
Markus Schlösser committed
108
	private void UpdateOrientation() {
Markus Schlösser's avatar
Markus Schlösser committed
109
110
111
		transform.rotation = GetRotation(orientation, facing);
	}

112
113
114
115
116
117
118
119
120
121
122
123
124
125
	private IEnumerator GetMovementOperation() {
		float direction = inputProvider.MoveDirection.x;

		if (direction < 0) {
			return Move(MovementDirection.Left);
		} else if (direction > 0) {
			return Move(MovementDirection.Right);
		} else if (inputProvider.JumpPressed) {
			return Jump();
		} else {
			return null;
		}
	}

Markus Schlösser's avatar
Markus Schlösser committed
126
	private static Quaternion GetRotation(Orientation orientation, MovementDirection facing) {
127
		Vector3 euler = new Vector3(0, 0, (int) orientation * -90.0f);
Markus Schlösser's avatar
Markus Schlösser committed
128
129
130
131
132
133
134
135
136
137
138
139
140
		switch (orientation) {
			case Orientation.Left:
			case Orientation.Right:
				euler.x = facing == MovementDirection.Right ? 0 : 180.0f;
				break;

			case Orientation.Up:
			case Orientation.Down:
				euler.y = facing == MovementDirection.Right ? 0 : 180.0f;
				break;

			default:
				throw new ArgumentOutOfRangeException();
141
142
		}

Markus Schlösser's avatar
Markus Schlösser committed
143
		return Quaternion.Euler(euler);
Markus Schlösser's avatar
Markus Schlösser committed
144
145
	}

146
	private static Vector3Int GetDirectionVector(Orientation o) {
147
148
149
150
151
152
153
154
155
156
157
		switch (o) {
			case Orientation.Up: return Vector3Int.up;
			case Orientation.Left: return Vector3Int.left;
			case Orientation.Right: return Vector3Int.right;
			case Orientation.Down: return Vector3Int.down;
			default:
				throw new ArgumentOutOfRangeException();
		}
	}

	private IEnumerator Move(MovementDirection direction) {
Markus Schlösser's avatar
Markus Schlösser committed
158
		List<IEnumerator> route = new List<IEnumerator>();
159
160

		Orientation o = orientation;
Markus Schlösser's avatar
Markus Schlösser committed
161
		Vector3Int cellPos = tilemap.WorldToCell(transform.position);
162
163
164
165
166
		bool isCompleteRoute = false;
		bool isValidRoute = true;

		int numSteps = 0;

167
		route.Add(Move(o.RotateClockwise((int) direction), 0.5f, MOVE_ANIMATION_TIME_PER_TILE * 0.5f));
Markus Schlösser's avatar
Markus Schlösser committed
168

169
170
171
172
173
174
		while (!isCompleteRoute && isValidRoute) {
			if (numSteps++ > MAX_STEPS) {
				isValidRoute = false;
				break;
			}

175
176
177
			Orientation directionOrientation = o.RotateClockwise((int) direction);
			Vector3Int directionVec = GetDirectionVector(directionOrientation);
			Vector3Int downVec = GetDirectionVector(o.GetDown());
178

179
			Orientation enterFace = directionOrientation.GetDown();
180

Markus Schlösser's avatar
Markus Schlösser committed
181
			Vector3Int adjacentCellPos = cellPos + directionVec;
182
183
184
185
			Vector3Int adjacentDownCellPos = adjacentCellPos + downVec;
			RotatedTile adjacentTile = tilemap.GetTile<RotatedTile>(adjacentCellPos);
			RotatedTile adjacentDownTile = tilemap.GetTile<RotatedTile>(adjacentDownCellPos);

Markus Schlösser's avatar
Markus Schlösser committed
186
187
			Debug.DrawLine(tilemap.GetCellCenterWorld(cellPos), tilemap.GetCellCenterWorld(adjacentCellPos), adjacentTile == null ? Color.red : Color.green);
			Debug.DrawLine(tilemap.GetCellCenterWorld(cellPos), tilemap.GetCellCenterWorld(adjacentDownCellPos), adjacentDownTile == null ? Color.red : Color.green);
188
189

			if (adjacentTile != null) {
Markus Schlösser's avatar
Markus Schlösser committed
190
				cellPos += directionVec;
191
192
193
				switch (direction) {
					case MovementDirection.Left:
						if (adjacentTile[enterFace].enter == OnEnterAction.MoveConcaveRight) {
194
							o = o.GetRight();
195
							route.Add(Rotate(directionOrientation, directionOrientation.GetRight(), o, CONCAVE_RADIUS, CONCAVE_ANIMATION_TIME));
196
197
198
199
200
201
202
203
						} else {
							isValidRoute = false;
						}

						break;

					case MovementDirection.Right:
						if (adjacentTile[enterFace].enter == OnEnterAction.MoveConcaveLeft) {
204
							o = o.GetLeft();
205
							route.Add(Rotate(directionOrientation, directionOrientation.GetLeft(), o, CONCAVE_RADIUS, CONCAVE_ANIMATION_TIME));
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
						} else {
							isValidRoute = false;
						}

						break;

					default:
						throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
				}
			} else if (adjacentDownTile != null) {
				switch (direction) {
					case MovementDirection.Left:
						switch (adjacentDownTile[o].left) {
							case OnWalkOverAction.Invalid:
								isValidRoute = false;
								break;

							case OnWalkOverAction.MoveToCenter:
Markus Schlösser's avatar
Markus Schlösser committed
224
								cellPos += directionVec;
225
								isCompleteRoute = true;
226
								route.Add(Move(directionOrientation, 0.5f, MOVE_ANIMATION_TIME_PER_TILE * 0.5f));
227
228
229
								break;

							case OnWalkOverAction.MoveConvex:
230
								cellPos += directionVec * 2 + downVec;
231
								o = o.GetLeft();
232
								route.Add(Rotate(directionOrientation, directionOrientation.GetLeft(), o, CONVEX_RADIUS, CONVEX_ANIMATION_TIME));
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
								break;

							default:
								throw new ArgumentOutOfRangeException();
						}

						break;

					case MovementDirection.Right:
						switch (adjacentDownTile[o].right) {
							case OnWalkOverAction.Invalid:
								isValidRoute = false;
								break;

							case OnWalkOverAction.MoveToCenter:
Markus Schlösser's avatar
Markus Schlösser committed
248
								cellPos += directionVec;
249
								isCompleteRoute = true;
250
								route.Add(Move(directionOrientation, 0.5f, MOVE_ANIMATION_TIME_PER_TILE * 0.5f));
251
252
253
								break;

							case OnWalkOverAction.MoveConvex:
254
								cellPos += directionVec * 2 + downVec;
255
								o = o.GetRight();
256
								route.Add(Rotate(directionOrientation, directionOrientation.GetRight(), o, CONVEX_RADIUS, CONVEX_ANIMATION_TIME));
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
								break;

							default:
								throw new ArgumentOutOfRangeException();
						}

						break;

					default:
						throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
				}
			} else {
				isValidRoute = false;
			}
		}

Markus Schlösser's avatar
Markus Schlösser committed
273
274
275
		facing = direction;
		UpdateOrientation();

276
		if (isValidRoute) {
Markus Schlösser's avatar
Markus Schlösser committed
277
278
			foreach (IEnumerator a in route) {
				yield return a;
279
			}
Markus Schlösser's avatar
Markus Schlösser committed
280
281
282
283
284
285
286

			IEnumerator movement = GetMovementOperation();
			if (movement != null) {
				movementRoutine = StartCoroutine(movement);
			} else {
				movementRoutine = null;
			}
Markus Schlösser's avatar
Markus Schlösser committed
287
288
		} else {
			animator.Play("HeadShake");
289
		}
290
	}
Markus Schlösser's avatar
Markus Schlösser committed
291
292
293
294
295

	private IEnumerator Jump() {
		Vector3Int celllPos = tilemap.WorldToCell(transform.position);
		Vector3Int direction = GetDirectionVector(orientation);
		RotatedTile tile = null;
Markus Schlösser's avatar
Markus Schlösser committed
296
297
		int i = 0;
		for (; i < MAX_STEPS; ++i) {
Markus Schlösser's avatar
Markus Schlösser committed
298
299
300
301
302
303
304
305
306
			celllPos += direction;
			RotatedTile hit = tilemap.GetTile<RotatedTile>(celllPos);
			if (hit != null) {
				tile = hit;
				break;
			}
		}

		if (tile != null) {
Markus Schlösser's avatar
Markus Schlösser committed
307
308
309
310
			animator.SetBool("isFalling", true);
			orientation = orientation.GetDown();
			UpdateOrientation();

311
312
313
			if (i != 0) {
				yield return Move(orientation.GetDown(), i, i * JUMP_ANIMATION_TIME_PER_TILE);
			}
Markus Schlösser's avatar
Markus Schlösser committed
314

315
			animator.SetBool("isFalling", false);
Markus Schlösser's avatar
Markus Schlösser committed
316

Markus Schlösser's avatar
Markus Schlösser committed
317
			Debug.DrawLine(tilemap.GetCellCenterWorld(tilemap.WorldToCell(transform.position)), tilemap.GetCellCenterWorld(celllPos), Color.red);
Markus Schlösser's avatar
Markus Schlösser committed
318
			OnLandAction action = tile[orientation].land;
Markus Schlösser's avatar
Markus Schlösser committed
319
320
321

			switch (action) {
				case OnLandAction.None:
Markus Schlösser's avatar
Markus Schlösser committed
322
					transform.position = tilemap.GetCellCenterWorld(celllPos - direction);
323
					movementRoutine = null;
Markus Schlösser's avatar
Markus Schlösser committed
324
325
326
					break;

				case OnLandAction.MoveConcaveLeft:
Markus Schlösser's avatar
Markus Schlösser committed
327
					transform.position = tilemap.GetCellCenterWorld(celllPos);
Markus Schlösser's avatar
Markus Schlösser committed
328
					animator.SetTrigger("shouldSlide");
Markus Schlösser's avatar
Markus Schlösser committed
329
330
331
332
					yield return Move(MovementDirection.Left);
					break;

				case OnLandAction.MoveConcaveRight:
Markus Schlösser's avatar
Markus Schlösser committed
333
					transform.position = tilemap.GetCellCenterWorld(celllPos);
Markus Schlösser's avatar
Markus Schlösser committed
334
					animator.SetTrigger("shouldSlide");
Markus Schlösser's avatar
Markus Schlösser committed
335
336
337
338
					yield return Move(MovementDirection.Right);
					break;

				case OnLandAction.MoveConvexLeft:
339
340
					transform.position = tilemap.GetCellCenterWorld(celllPos - direction);
					facing = MovementDirection.Left;
Markus Schlösser's avatar
Markus Schlösser committed
341
					UpdateOrientation();
Markus Schlösser's avatar
Markus Schlösser committed
342
					animator.SetTrigger("shouldSlide");
343
					yield return Rotate(orientation.GetLeft(), orientation.GetDown(), orientation.GetLeft(), 1.0f, 0.2f);
Markus Schlösser's avatar
Markus Schlösser committed
344
345
346
347
					yield return Move(MovementDirection.Left);
					break;

				case OnLandAction.MoveConvexRight:
348
349
					transform.position = tilemap.GetCellCenterWorld(celllPos - direction);
					facing = MovementDirection.Right;
Markus Schlösser's avatar
Markus Schlösser committed
350
					UpdateOrientation();
Markus Schlösser's avatar
Markus Schlösser committed
351
					animator.SetTrigger("shouldSlide");
352
					yield return Rotate(orientation.GetRight(), orientation.GetDown(), orientation.GetRight(), 1.0f, 0.1f);
Markus Schlösser's avatar
Markus Schlösser committed
353
354
355
356
357
358
					yield return Move(MovementDirection.Right);
					break;

				default:
					throw new ArgumentOutOfRangeException();
			}
Markus Schlösser's avatar
Markus Schlösser committed
359
		} else {
360
			animator.Play("PeekingStatic");
Markus Schlösser's avatar
Markus Schlösser committed
361
362
		}
	}
Markus Schlösser's avatar
Markus Schlösser committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377

	private IEnumerator Move(Orientation direction, float distance, float time) {
		Vector3 vec = GetDirectionVector(direction);
		vec *= distance;

		Vector3 start = transform.position;

		for (float t = 0; t <= time; t += Time.deltaTime) {
			transform.position = Vector3.Lerp(start, start + vec, t / time);
			yield return null;
		}

		transform.position = start + vec;
	}

378
	private IEnumerator Rotate(Orientation startDirection, Orientation endDirection, Orientation target, float curveRadius, float time) {
Markus Schlösser's avatar
Markus Schlösser committed
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
		Vector3 startDir = GetDirectionVector(startDirection);
		Vector3 endDir = GetDirectionVector(endDirection);

		Vector3 startPos = transform.position;
		Vector3 endPos = transform.position + (startDir + endDir) * curveRadius;

		Vector3 rotationCenter = startPos + endDir * curveRadius;

		Quaternion startRotation = transform.rotation;
		Quaternion endRotation = GetRotation(target, facing);

		Quaternion targetRortation = Quaternion.Euler(0, 0, startDirection.GetLeft() == endDirection ? 90.0f : -90.0f);

		for (float t = 0; t <= time; t += Time.deltaTime) {
			Quaternion rot = Quaternion.Lerp(Quaternion.identity, targetRortation, t / time);
			Debug.DrawLine(transform.position, rotationCenter, Color.red);

			transform.position = rotationCenter - rot * endDir * curveRadius;
			transform.rotation = Quaternion.Slerp(startRotation, endRotation, t / time);

			yield return null;
		}

		transform.position = endPos;
		orientation = target;
		UpdateOrientation();
	}
Marcel Kuehn's avatar
Marcel Kuehn committed
406

Markus Schlösser's avatar
Markus Schlösser committed
407
408
409
410
	private IEnumerator Die() {
		deathEffect.Play(true);
		col.enabled = false;
		sprite.enabled = false;
Markus Schlösser's avatar
Markus Schlösser committed
411
		headlight.SetActive(false);
Markus Schlösser's avatar
Markus Schlösser committed
412
413
414

		yield return new WaitForSeconds(0.1f);

415
416
417
418
419
420
421
		// TODO: This call is really inefficient
		IResetable[] resetables = FindObjectsOfType<MonoBehaviour>().OfType<IResetable>().ToArray();
		foreach (IResetable r in resetables) {
			r.ResetToLevelBegin();
		}
	}

Markus Schlösser's avatar
Markus Schlösser committed
422
423
424
425
426
427
428
	public void LevelEnd() {
		animator.Play("LevelEnd");
		enabled = false;
		col.enabled = false;
		headlight.SetActive(false);
	}

429
	public void ResetToLevelBegin() {
Markus Schlösser's avatar
Markus Schlösser committed
430
431
432
433
434
		if (movementRoutine != null) {
			StopCoroutine(movementRoutine);
			movementRoutine = null;
		}

Markus Schlösser's avatar
Markus Schlösser committed
435
436
437
438
439
		transform.position = startingPosition;
		orientation = startingOrientation;

		sprite.enabled = true;
		col.enabled = true;
Markus Schlösser's avatar
Markus Schlösser committed
440
		headlight.SetActive(true);
Markus Schlösser's avatar
Markus Schlösser committed
441

442
443
444
445
446
447
		animator.SetBool("isFalling", false);
		animator.SetBool("isRunning", false);
		animator.SetBool("isPeeking", false);
		animator.SetBool("shouldSlide", false);
		animator.Play("Idle");

Marcel Kuehn's avatar
Marcel Kuehn committed
448
449
		UpdateOrientation();
	}
450
}