Learn how to make Parallax Background in Unity.
using UnityEngine;
public class ParallaxBackground : MonoBehaviour
{
private float length, startPos;
public GameObject cam;
public float parallaxEffect;
private void Start()
{
startPos = transform.position.x;
length = GetComponent().bounds.size.x;
}
private void FixedUpdate()
{
float temp = (cam.transform.position.x * (1 - parallaxEffect));
float dist = (cam.transform.position.x * parallaxEffect);
transform.position = new Vector3(startPos + dist, transform.position.y, transform position.z);
if (temp > startPos + length) startPos += length;
else if (temp < startPos - length) startPos -= length;
}
}
Under the Camera object, create a parent object that will hold our backgrounds and place the backgrounds inside it.
In the example, there are 5 backgrounds, so I set the Order in Layer
values in Additional Settings in the following order: 5, 4, 3, 2, 1.
Select all 5 backgrounds and duplicate
them. Set the X value to 18
for the duplicates, then duplicate
them again and set the X value to -18
.
Group each copy under the main object.
Assign the ParallaxBackground
script we created to the main objects. Assign the camera to the Cam
field and set the Parallax Effect
as follows:
The images in this article were created by penusbmic.