I’m rotating my player with the slope of my terrain by using a raycast. My problem is that the rotation is really choppy. How would I smooth it out?
Here’s my code:
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit)){
transform.rotation = Quaternion.LookRotation(Vector3.Cross(transform.right, hit.normal));
}
}
Instead of using hit.normal instantly and directly, average it over time by keeping an “accumulated” hit.normal and slowly moving it towards the hit.normal of this frame’s raycast.
This is just such a simple low-pass filter:
private Vector3 normalAccumulator;
const float Snappiness = 1.0f; // larger is faster response
Then when you hit:
normalAccumulator = Vector3.Lerp( normalAccumulator, hit.normal, Snappiness * Time.deltaTime);
Now use normalAccumulator in your rotate thing above.
1 Like
That did the trick!
Here’s what I ended up with:
private Vector3 normalAccumulator;
const float Snappiness = 1.0f; // larger is faster response
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit)){
Vector3 insert = new Vector3(0,0,0);
normalAccumulator = Vector3.Lerp( normalAccumulator, hit.normal, Snappiness * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(Vector3.Cross(transform.right, normalAccumulator));
}
}
2 Likes