Thursday, November 5, 2015

Parallax scrolling

Repeating background (tiling)

There are several ways how to create parallax scrolling. I was using different approach until I found that following one is the best:
  1. Use the Quad 3D game object
  2. Create Material:
     a. Material's shader needs to be set as Mobile>Particles>Alpha Blended
     b. Texture placed over the material needs to have Wrap Mode set to Repeat
  3. Attach the material to the quad
Quad with material
In the next step create a script and based on the screen width:
  1. We compute the tiling parameter, i.e. how many times the texture on the material has to repeat horizontally to cover the whole screen width.
  2. We have to resize the quad so repeating texture can fit it precisely (tiling parameter * texture width). Note that I am using for the game the ratio 1 pixel = 1 game unit and I force the screen resolution to be always 360px height with computed width based on the screen aspect ratio. The computed width has almost always the same value 640px, since most TV screens are 16:9. The code looks like the one below:

// How many textures are per screen width
float count = Mathf.Ceil ( Screen.width / render.material.mainTexture.width / MyScreen.pixelsToUnits );

// Set the new size to the quad
transform.localScale = new Vector3(count * render.material.mainTexture.width, transform.localScale.y, 1);

// Set the tiling parameter of the material
render.material.mainTextureScale = new Vector2(count, 1);
Repeating background

Moving with the background

The background is moved by changing the offset of the texture attached to the material:
public class BackgroundMove : MonoBehaviour 
{
 public float speed = 1.2f;
 private Material material = null;
 private Vector2 offset;
 
 void Start () 
 {
  Renderer render = GetComponent();
  if ( render && render.material )
  {
   // Save the material reference and the texture offset value
   material = render.material;
   offset = material.mainTextureOffset;
  }
 }

 // Update is called once per frame
 void Update () 
 {
  // Move the offset ("Wrap mode" has to be set to "Repeat" on a sprite)
  if ( material )
  {
   offset.x += speed * Time.deltaTime;
   material.mainTextureOffset = offset;
  }
 }
}
Creating the illusion of parallax moving background is achieved by moving with further objects (background images) slower than closer objects (sorry for the low quality):

No comments:

Post a Comment