DEV Community

Cover image for Create parallax effect of a 2D game background (Unity3D)
Nafis Jaman
Nafis Jaman

Posted on

Create parallax effect of a 2D game background (Unity3D)

We often see the parallax effect in the background of 2D games. We can easily make this with Unity3D. To do this, we need to create a material. Change the shader type to Unlit/Texture.

Image description

Then select the background texture. Create a Quad. Resize it. Drag the material into material portion in mesh renderer.

Image description

Create a script name "Parallax" and attach to the quad. Open the script and paste the code.

`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parallax : MonoBehaviour
{
MeshRenderer meshRenderer;
[SerializeField]float animationSpeed = .5f;

private void Awake()
{
    meshRenderer = GetComponent<MeshRenderer>();
}
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    meshRenderer.material.mainTextureOffset += new Vector2(animationSpeed * Time.deltaTime, 0);
}
Enter fullscreen mode Exit fullscreen mode

}
`

Here the mesh renderer attribute access the background material. We just change the offset value over frame so that it can rotate on X axis.

Image description

That's it. Your parallax background is ready for the game.

Happy coding ☺️!

Top comments (0)