working on fpp locomotion, camera spring
This commit is contained in:
59
Assets/jelycho/Code/Player/CameraSpring.cs
Normal file
59
Assets/jelycho/Code/Player/CameraSpring.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace RealityReboot.jelycho.Player {
|
||||
public class CameraSpring : MonoBehaviour {
|
||||
[Min(0.01f), SerializeField] float m_HalfLife = 0.075f;
|
||||
[SerializeField] float m_Frequency = 10.0f;
|
||||
[SerializeField] float m_ForwardAngularDisplacement = 1.0f;
|
||||
[SerializeField] float m_SidewaysAngularDisplacement = 1.0f;
|
||||
[SerializeField] float m_HeightAngularDisplacement = 2.0f;
|
||||
[SerializeField] float m_LinearDisplacement = 0.05f;
|
||||
|
||||
Vector3 m_SpringPosition;
|
||||
Vector3 m_SpringVelocity;
|
||||
|
||||
public void Initialize() {
|
||||
m_SpringPosition = transform.position;
|
||||
m_SpringVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
public void UpdateSpring(float deltaTime, Vector3 up, Vector3 right, Vector3 forward) {
|
||||
Spring(ref m_SpringPosition,
|
||||
ref m_SpringVelocity,
|
||||
transform.position,
|
||||
m_HalfLife,
|
||||
m_Frequency,
|
||||
deltaTime);
|
||||
|
||||
Vector3 localSpringPosition = m_SpringPosition - transform.position;
|
||||
float springHeight = Vector3.Dot(localSpringPosition, up);
|
||||
float springForward = Vector3.Dot(localSpringPosition, forward);
|
||||
float springSideways = Vector3.Dot(localSpringPosition, right);
|
||||
|
||||
float pitch = -springHeight * m_HeightAngularDisplacement + -springForward * m_ForwardAngularDisplacement;
|
||||
transform.localEulerAngles = new Vector3(pitch,
|
||||
0.0f,
|
||||
springSideways * m_SidewaysAngularDisplacement);
|
||||
}
|
||||
|
||||
// Source: https://allenchou.net/2015/04/game-math-precise-control-over-numeric-springing/
|
||||
static void Spring(ref Vector3 current,
|
||||
ref Vector3 velocity,
|
||||
Vector3 target,
|
||||
float halfLife,
|
||||
float frequency,
|
||||
float timeStep) {
|
||||
|
||||
float dampingRatio = -Mathf.Log(0.5f) / (frequency * halfLife);
|
||||
float f = 1.0f + 2.0f * timeStep * dampingRatio * frequency;
|
||||
float oo = frequency * frequency;
|
||||
float hoo = timeStep * oo;
|
||||
float hhoo = timeStep * hoo;
|
||||
float detInv = 1.0f / (f + hhoo);
|
||||
Vector3 detX = f * current + timeStep * velocity + hhoo * target;
|
||||
Vector3 detV = velocity + hoo * (target - current);
|
||||
current = detX * detInv;
|
||||
velocity = detV * detInv;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user