Jittery background when implementing parallax effect
I'm trying to create a 2D sidescroller that implements a parallax effect for the background (there is also a ground which does not use the effect). The camera follows the player, and the player controls a unit that can move left and right. In other words, there is no set speed for the ground to move at so I can't just have the background scroll at a fraction of the speed as the ground.
My current solution is to move the background a fraction of the player's x velocity. I add this in the update function of the backgrounds script:
transform.position = transform.position + Vector3.right * playerRb.velocity.x * Time.deltaTime * 0.9f;
Here, i'm trying to make the background scroll at 90% of the player's speed. This actually seems to work, except for the fact that it is extremely jittery when I test it in Unity (I left out infinite scrolling for now).
Does anyone know why this may happen? Is there something wrong with the way that I position the background images?
That looks like it's jumping backwards sometimes. Check if playerRb.velocity.x becomes negative at any time.
I think you might be right, except ins$$anonymous$$d of negative velocities, I may have had a negative acceleration. I think the velocity wasn't strictly increasing like I expected to, it jumped backwards sometimes, which may have caused the jittering effect. Thanks!
Answer by CapitalLlama · Aug 30, 2016 at 07:23 AM
You should be able to do something simple like this (assuming you only want the background moving on the X-axis
Vector2 _x= new Vector2 (player.transform.position.x, 0);
transform.position = _x * 0.9f;
player is the gameObject of the player
I tried this myself and it didn't have any stuttering. Let me know how it works out for you!
This worked great for me! I'm not sure why I was using velocity ins$$anonymous$$d of position. Thanks!