-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathAerialMovementActionSO.cs
More file actions
74 lines (61 loc) · 2.43 KB
/
AerialMovementActionSO.cs
File metadata and controls
74 lines (61 loc) · 2.43 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
68
69
70
71
72
73
74
using UnityEngine;
using UOP1.StateMachine;
using UOP1.StateMachine.ScriptableObjects;
/// <summary>
/// This Action handles horizontal movement while in the air, keeping momentum, simulating air resistance, and accelerating towards the desired speed.
/// </summary>
[CreateAssetMenu(fileName = "AerialMovement", menuName = "State Machines/Actions/Aerial Movement")]
public class AerialMovementActionSO : StateActionSO
{
public float Speed => _speed;
public float Acceleration => _acceleration;
[Tooltip("Desired horizontal movement speed while in the air")]
[SerializeField] [Range(0.1f, 100f)] private float _speed = 10f;
[Tooltip("The acceleration applied to reach the desired speed")]
[SerializeField] [Range(0.1f, 100f)] private float _acceleration = 20f;
protected override StateAction CreateAction() => new AerialMovementAction();
}
public class AerialMovementAction : StateAction
{
private new AerialMovementActionSO OriginSO => (AerialMovementActionSO)base.OriginSO;
private Protagonist _protagonist;
public override void Awake(StateMachine stateMachine)
{
_protagonist = stateMachine.GetComponent<Protagonist>();
}
public override void OnUpdate()
{
Vector3 velocity = _protagonist.movementVector;
Vector2 horizontalInput = new Vector2(_protagonist.movementInput.x, _protagonist.movementInput.z);
float acceleration = OriginSO.Acceleration;
float speed = OriginSO.Speed;
Vector2 horizontalVelocity = new Vector2(velocity.x, velocity.z);
SetHorizontalVelocity(ref horizontalVelocity, horizontalInput, acceleration, speed);
velocity.x = horizontalVelocity.x;
velocity.z = horizontalVelocity.y;
_protagonist.movementVector = velocity;
}
private void SetHorizontalVelocity(ref Vector2 horizontalVelocity, Vector2 horizontalInput, float acceleration, float targetSpeed)
{
float inputMagnitude = horizontalInput.magnitude;
if (Mathf.Approximately(inputMagnitude, 0f))
{
ApplyAirResistance(ref horizontalVelocity);
}
else
{
targetSpeed *= inputMagnitude;
horizontalVelocity += horizontalInput * acceleration;
// Apply a speed limit
float horizontalSpeed = horizontalVelocity.magnitude;
if (targetSpeed < horizontalSpeed)
horizontalVelocity = horizontalVelocity / horizontalSpeed * targetSpeed;
}
}
private void ApplyAirResistance(ref Vector2 vector)
{
if (Mathf.Approximately(vector.sqrMagnitude, 0))
return;
vector -= vector.normalized * Protagonist.AIR_RESISTANCE * Time.deltaTime;
}
}