-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayerMovement.cs
More file actions
67 lines (56 loc) · 2.54 KB
/
PlayerMovement.cs
File metadata and controls
67 lines (56 loc) · 2.54 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
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody _body;
private PlayerInputController _inputController;
[SerializeField]
private PlayerConfigModule _playerConfig;
// Start is called before the first frame update
void Start()
{
_body = GetComponent<Rigidbody>();
_inputController = GetComponent<PlayerInputController>();
}
void FixedUpdate()
{
var currentDirection = _inputController.GetRequestedDirection();
if (currentDirection != Direction.None) {
var position = new Vector3(0, 1, 0);
var vector = GetMovementVector(currentDirection);
// we apply only one of stationary boost, reverse boost or turn boost, favoring them in that order
if (_playerConfig.StationaryBoost > 0 && !IsMoving()) {
_body.AddForceAtPosition(_playerConfig.StationaryBoost * vector, position, ForceMode.Impulse);
} else if (_playerConfig.ReverseBoost > 0 && _inputController.IsReversed()) {
_body.AddForceAtPosition(_playerConfig.ReverseBoost * vector, position, ForceMode.Impulse);
} else if (_playerConfig.TurnBoost > 0 && _inputController.IsTurned()) {
_body.AddForceAtPosition(_playerConfig.TurnBoost * vector, position, ForceMode.Impulse);
}
_body.AddForceAtPosition(_playerConfig.ContinuousForce * vector, position, ForceMode.Force);
}
}
// uses the player config's "stationary threshold" to determine if the player is moving
private bool IsMoving()
{
return _body.velocity.magnitude >= _playerConfig.StationaryThreshold;
}
// calculate the movement vector for the given direction
private Vector3 GetMovementVector(Direction direction)
{
var vector = direction switch {
Direction.East => new Vector3(1, 0, 0),
Direction.Northeast => new Vector3(1, 0, 1),
Direction.North => new Vector3(0, 0, 1),
Direction.Northwest => new Vector3(-1, 0, 1),
Direction.West => new Vector3(-1, 0, 0),
Direction.Southwest => new Vector3(-1, 0, -1),
Direction.South => new Vector3(0, 0, -1),
Direction.Southeast => new Vector3(1, 0, -1),
_ => Vector3.zero,
};
var mapRotation = Camera.main.transform.eulerAngles.y;
return mapRotation == 0 ? vector : Quaternion.AngleAxis(mapRotation, Vector3.up) * vector;
}
}