6 de jul. de 2017

Background Paralax - model 1

There are some ways to make the Background run as if the camera was moving.

In this example, we move the Gameobject with the SpriteRender with a child with another Gameobject with the same image (duplicate de Gameobject) in the scene and when it reachs the startPosition + hisSize, it comes back to the startPosition.





using UnityEngine;

public class Paralax : MonoBehaviour {

    public float scrollSpeed;
    public float tileSizeZ = 0;     // if changed in edit time, it uses this value for the size of the SPriteRenderer
                                    // Used in images that are shorter than the screen width

    private SpriteRenderer sprite;  // the SpriteRender of the GameObject
    private Vector3 startPosition;  // Start position of the GameObject
    

    void Start () {
        sprite = GetComponent<SpriteRenderer>();
        startPosition = transform.position;

        if (tileSizeZ == 0)
        {
            tileSizeZ = sprite.bounds.size.x;
        }
    }

    void Update () {
        /* Repeat works like:
         if Time.time * scrollSpeed < tileSizeZ, newPosition = Time.time * scrollSpeed
         else, newPosition = (Time.time * scrollSpeed) - (loopIndex * tileSizeZ) */
        float newPosition = Mathf.Repeat(Time.time * scrollSpeed, tileSizeZ);
        transform.position = startPosition + Vector3.left * newPosition;
    }
}

Nenhum comentário: