Search code examples
unity-game-engineparallax

Using Parallaxing for a 2D game in unity Understanding the Z axis


i'm using parallaxing for a 2D game in unity and basically, I'm moving the position of the backgrounds on the x axis whenever the camera moves (The camera moves right or left following the character). I'm having trouble understanding what this line means parallaxScales[i] = backgrounds[i].position.z * -1; Doesn't the z position have to do with depth? What exactly does it mean when you say position.z * -1 or position.z * 5. Its not affecting the actual depth of the backgrounds ive been using in the game (since they are moving left and right). So what exactly does it mean. why use the Z axis?

using UnityEngine;
using System.Collections;

public class Parallaxing : MonoBehaviour {


public Transform [] backgrounds;    
private float [] parallaxScales;   
public float smoothing = 1f;      

private Transform cam;             
private Vector3 previousCamPos;    


void Awake () 

{
    cam = Camera.main.transform; 
}

void Start ()

{
    previousCamPos = cam.position;
    parallaxScales = new float[backgrounds.Length]; 

    for (int i = 0; i < backgrounds.Length; i++)  
    {
        parallaxScales[i] = backgrounds[i].position.z * -1;

    }
}

void Update () 
{

    for (int i = 0; i < backgrounds.Length; i++)

    {

        float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i];

        float backgroundTargetPosX = backgrounds[i].position.x + parallax;   


        Vector3 backgroundTargetPos = new Vector3 (backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);


        backgrounds[i].position = Vector3.Lerp (backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);

    }

    previousCamPos = cam.position; 
}
}

Solution

  • This Parallaxing class is using the z value of the backgrounds to control the amount of parallax that gets applied to them. e.g. the higher the z the more movements happens to that background when the camera moves. Using the gameObjects Z value to control parallax is convinient because it allows you to easily see in the editor how much parallax will be applied to each object, and it doesn't require a custom script to be added to each object.