I’m trying to create a parallax effect in my 2D sidescroller that is not infinite. I’m placing biomes next to each other and each biome has its own parallax background. I want one biome’s background to end where the biome ends.
The biome has a Bounds bounds
field to determine its bounds.
First I’m setting each layers width to be approximately the length of the biome’s width considering the layer’s parallax factor:
float camWidth = MainCam.orthographicSize * 2 * MainCam.aspect;
float maxDistance = bounds.size.x;
float layerWidth = camWidth + (maxDistance * (1 - layer.ParallaxFactor));
renderer.size = new Vector2(layerWidth, renderer.size.y);
Then when moving the layers I implemented a feature to clamp each layer’s movement depending on the distance of the camera from the center of the bounds:
private void LateUpdate()
{
Vector2 camDistFromCenter = mainCam.transform.position - bounds.center;
for (int i = 0; i < layers.Length; i++)
{
var layer = layers[i];
float parallaxFactor = layer.ParallaxFactor;
float x = Mathf.Clamp(camDistFromCenter.x, bounds.min.x, bounds.max.x) * parallaxFactor;
layer.transform.position = new Vector3(bounds.center.x + x, layer.transform.position.y);
}
}
I want the clamp to be a smooth one instead of this hard clamp though. I tried to introduce another multiplier that slowly reduces to zero based on the distance of the camera and the bounds.min.x or bounds.max.x, but that would move each layer back to the center once decreasing instead of slowly stopping the layer. Of course the x value is added to the center as an offset, so I get why that’s happening, but I can’t seem to figure out a way to slowly stop the layers.
Maybe I’m overthinking and there’s a much straightforward way of achieving what I need. I’d be grateful for any suggestions!