Skip to content

Instantly share code, notes, and snippets.

@Domiii
Created May 26, 2018 11:02
Show Gist options
  • Save Domiii/ce1adb0561ef8c73593c05c2445bd3e4 to your computer and use it in GitHub Desktop.
Save Domiii/ce1adb0561ef8c73593c05c2445bd3e4 to your computer and use it in GitHub Desktop.
Simple horizontal repeating background in Unity (C#)
using UnityEngine;
using System.Collections;
/// <summary>
/// For this to work, you need a background sprite that is
/// 1) cyclical: it's left side connects seam-less with it's right side
/// 2) it must at least span the width of the camera view
/// 3) it must be repeated twice (so you actually have the same thing three times, implying at least three times the camera view width)
///
/// TODO: To make things simpler, you can just mirror a single sprite/texture and repeat it three times
/// TODO: Also add vertical infinite scrolling
/// </summary>
public class RepeatingBackground : MonoBehaviour
{
public Camera cam;
int splitN = 3;
float w;
float xOffset;
void Awake ()
{
if (!cam) {
cam = Camera.main;
}
var sprite = GetComponent<SpriteRenderer> ();
var bounds = sprite.bounds;
// the actual sprite width is only one third of the total background (which is repeated a total of three times)
w = bounds.extents.x * 2 / 3;
xOffset = transform.position.x;
}
void Update ()
{
var pos = transform.position;
var xDist = cam.transform.position.x - xOffset;
var ix = (int)(xDist / w);
pos.x = ix * w + xOffset;
transform.position = pos;
}
#if UNITY_EDITOR
/// <summary>
/// Draw the tripple split up of the texture
/// </summary>
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.yellow;
var renderer = GetComponent<SpriteRenderer> ();
if (renderer) {
var bounds = renderer.bounds;
var w = bounds.extents.x * 2 / 3;
var h = bounds.extents.y * 2;
var hHalf = h / 2;
var yBase = bounds.center.y - h;
var dY = Vector2.up * 2 * h; // draw twice the height
for (var i = 0; i <= splitN; ++i) {
var lo = new Vector2(bounds.min.x + i * w, yBase);
var hi = lo + dY;
Gizmos.DrawLine (lo, hi);
}
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment