Watch Video Tutorial
Code for Infinite Background Scrolling IN Unity 2d game.
Code for Infinite Background Scrolling IN Unity 2d game.
using UnityEngine; using System.Collections; public class Scroll : MonoBehaviour { public float backGroundSize; private Transform cameraTransform; public Transform[] layers; private float viewZone = 0; private int leftIndex; private int rightIndex; private void Start() { cameraTransform = Camera.main.transform; leftIndex = 0; rightIndex = layers.Length - 1; } void Update() { if (cameraTransform.position.x < (layers[leftIndex].transform.position.x + viewZone)) ScrollLeft(); if (cameraTransform.position.x > (layers[rightIndex].transform.position.x - viewZone)) ScrollRight(); } private void ScrollLeft() { layers[rightIndex].position = new Vector3 (1f * (layers[leftIndex].position.x - backGroundSize), 0f, 0f); leftIndex = rightIndex; rightIndex--; if (rightIndex < 0) rightIndex = layers.Length - 1; } private void ScrollRight() { layers[leftIndex].position = new Vector3 (1f * (layers[leftIndex].position.x + backGroundSize), 0f, 10f); rightIndex = leftIndex; leftIndex++; if (leftIndex == layers.Length) leftIndex = 0; } }
This comment has been removed by the author.
ReplyDeleteNice tutorial. Thanks for sharing the code.
ReplyDeleteOn Scrolling right there was a flickering and i get fixed by modifying your ScrollRight() code as below:
private void ScrollRight()
{
layers[leftIndex].position =
new Vector3
(1f * (layers[rightIndex].position.x + backGroundSize), 0f, 0f);
rightIndex = leftIndex;
leftIndex++;
if (leftIndex == layers.Length)
leftIndex = 0;
}
wow
Deletethenks.