Search Unity

Infinite background loop

Discussion in 'Scripting' started by Simonxzx, Mar 5, 2015.

  1. Simonxzx

    Simonxzx

    Joined:
    Feb 22, 2015
    Posts:
    129
    Hi everyone, i'm developing a 2D game in which i want to add a background that scrolls down in an infinite way, as time passes. How can i do it? Thank you very much !
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    The easiest way to do this is to have 2 identical background objects, let's say one at (0,0,0) and one at (0,10,0) (have them line up edge to edge; I'm going to assume for this that they are 10 units tall). Put these both under a single parent object. Now, something like this on the parent: (C#)

    Code (csharp):
    1.  
    2. public float moveSpeed = 2f;
    3. public float loopMax = 10f;
    4. public float loopMin = 0f;
    5. void Update() {
    6. transform.position += new Vector3(0f, moveSpeed * Time.deltaTime, 0f);
    7. if (transform.position.y > loopMax) {
    8. transform.position += new Vector3 (0f, loopMin - loopMax, 0f);
    9. }
    10. }
    11.  
    This moves the object upwards until its Y reaches loopMax, at which point it moves it down to loopMin - well, almost to loopMin. This will actually result in a smoother animation than going to loopMin, because it doesn't discard the little fractions of a unit that the background moves in a frame.
     
  3. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    another way that you can do it is by creating a tall atlas file containing the images.. just like a movie is..


    img1
    img2
    img3
    img4

    but to make it loop seamless, you simply add the first frame at the end again...

    img1
    img2
    img3
    img4
    img1

    the image 4 must to be coherent with 1.
    add an animation to it to pass from frame1 (top) to frame1 (bottom)... and set wrap mode to loop..
     
  4. Simonxzx

    Simonxzx

    Joined:
    Feb 22, 2015
    Posts:
    129
    Ok, thank you very much guys! ;)
     
  5. Kaikaze

    Kaikaze

    Joined:
    Nov 14, 2014
    Posts:
    3
    An alternative approach would be to have the background move with the camera and just pan the UVs in the desired direction.