-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlayerMovement.cs
86 lines (68 loc) · 2.64 KB
/
PlayerMovement.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
using UnityEngine;
using FishNet;
using DerailedDeliveries.Framework.InputParser;
namespace DerailedDeliveries.Framework.Gameplay.Player
{
/// <summary>
/// A class responsible for handling the player's movement.
/// </summary>
[RequireComponent(typeof(Rigidbody), typeof(PlayerInputParser))]
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private float _speed = 2;
[SerializeField]
private float _maxSpeed = 2;
[SerializeField]
private float _rotationSpeed = 50;
private PlayerInputParser _playerInputParser;
private Rigidbody _rigidbody;
private Vector2 _playerInput;
private void Awake()
{
_rigidbody = gameObject.GetComponent<Rigidbody>();
_playerInputParser = gameObject.GetComponent<PlayerInputParser>();
}
private void OnEnable()
{
_playerInputParser.OnMove += SetMovementVector;
InstanceFinder.TimeManager.OnTick += UpdatePhysics;
}
private void OnDisable()
{
_playerInputParser.OnMove -= SetMovementVector;
if (InstanceFinder.TimeManager != null)
InstanceFinder.TimeManager.OnTick -= UpdatePhysics;
}
private void SetMovementVector(Vector2 playerInput) => _playerInput = playerInput;
private void UpdatePhysics()
{
if (_playerInput == Vector2.zero)
return;
Vector3 cameraForward = UnityEngine.Camera.main.transform.forward;
cameraForward.y = 0;
// Transform the input from local space to world space using the camera's forward direction.
Vector3 playerInput = cameraForward * _playerInput.y + UnityEngine.Camera.main.transform.right * _playerInput.x;
UpdateVelocity(playerInput);
UpdateRotation(playerInput.normalized);
}
private void UpdateRotation(Vector3 input)
{
Vector3 upwardsVector = transform.parent == null
? Vector3.up
: transform.parent.up;
gameObject.transform.rotation =
Quaternion.Slerp
(
gameObject.transform.rotation,
Quaternion.LookRotation(input, upwardsVector),
Mathf.Clamp01(_rotationSpeed * Time.deltaTime)
);
}
private void UpdateVelocity(Vector3 input)
{
Vector3 newForce = _rigidbody.velocity + input * _speed;
_rigidbody.AddForce(Vector3.ClampMagnitude(newForce, _maxSpeed));
}
}
}