2d camera follow script shaking
Hi, I just implemented a smooth camera follow script with some clamping to prevent the camera from going out of bounds.
The problem here is that when the camera moves, the sprite looks like it's jerking and stuttering ever so slightly (causing the pixels to look a bit blurry). The camera has a noticeable stutter on it too when playing normally.
Here is the script that handles camera movement:
float height = 2f * Camera.main.orthographicSize;
float width = height * Camera.main.aspect;
Vector3 targetPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, targetPosition, smoothFactor * Time.fixedDeltaTime);
smoothedPosition.x = Mathf.Clamp(smoothedPosition.x, leftBound + width / 2f, rightBound - width / 2f);
smoothedPosition.y = Mathf.Clamp(smoothedPosition.y, bottomBound + height / 2f, topBound - height / 2f);
transform.position = smoothedPosition;
This code gets called from the FixedUpdate() method. To me it seems like it jerks every time the position gets updated (which results in rapid stutters)
I've tested it with only "target position", it still gets the same effect (so it has nothing to do with the smoothing).
I've tested it with adding an extra lerp on the final transform.position, no changes.
Lastly, I've tried with LateUpdate() and LateUpdate() has a noticeable improvement, but there are definitely still slight stutters as well.
Unsure what could be the problem. Any advice? Thank you!
Answer by khoutas98 · Mar 08 at 11:32 PM
Funnily enough I realized the problem shortly after (unfortunately I did do digging for an hour before asking this question)
The player movement script and the camera movement script were both in different functions. The player's movement was in Update() (which is shouldn't ever be I must've wrote this script quickly and moved on), and the camera movement was in FixedUpdate(). Both were being updated at differing rates causing this problem. I moved them both to the same update (FixedUpdate()) and now the problem is gone.
Your answer
Follow this Question
Related Questions
How do I get pixel perfect camera movement using point (no filter) tilemaps and sprites? 0 Answers
Unity 2D Camera Bounds for Vertical Infinite Gamd 0 Answers
Camera moves impossibly fast, and can't see any object 1 Answer
Camera not following 2D character when the character reaches the ground. 0 Answers