Created
March 20, 2014 17:33
-
-
Save poemdexter/9669365 to your computer and use it in GitHub Desktop.
Scrolling Background for Unity3D. Set tile prefab, amount of tiles, tileWidth, and speed in inspector.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class ScrollingBackground : MonoBehaviour | |
{ | |
public GameObject backgroundTile; | |
public int tileAmount; | |
public float tileWidth; | |
public float backgroundSpeed; | |
private GameObject[] backgroundPool; | |
private int leftBackgroundTile; | |
private int rightBackgroundTile; | |
private int wrapXLimit; | |
void Start() | |
{ | |
backgroundPool = new GameObject[tileAmount]; | |
for (int j = 0; j<backgroundPool.Length; j++) { | |
backgroundPool[j] = (GameObject)Instantiate(backgroundTile); | |
} | |
wrapXLimit = Mathf.CeilToInt(tileAmount / 2); | |
for (int j = 0; j < tileAmount; j++) { | |
float x = (j - wrapXLimit) * tileWidth; | |
float y = backgroundPool[j].transform.position.y; | |
backgroundPool[j].transform.position = new Vector2(x,y); | |
} | |
leftBackgroundTile = 0; | |
rightBackgroundTile = tileAmount; | |
} | |
void Update() | |
{ | |
for (int j = 0; j < tileAmount; j++) { | |
backgroundPool[j].transform.Translate(-Vector2.right * backgroundSpeed * Time.deltaTime); | |
} | |
Vector2 bgPos = backgroundPool[leftBackgroundTile].transform.position; | |
if (bgPos.x < -wrapXLimit * tileWidth) { | |
Vector2 newPosition = bgPos + (Vector2.right * (tileWidth * (backgroundPool.Length))); | |
backgroundPool[leftBackgroundTile].transform.position = newPosition; | |
leftBackgroundTile = (leftBackgroundTile + 1 < backgroundPool.Length) ? leftBackgroundTile + 1 : 0; | |
rightBackgroundTile = (rightBackgroundTile + 1 < backgroundPool.Length) ? rightBackgroundTile + 1 : 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment