Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Created February 23, 2022 23:27
Show Gist options
  • Save kurtdekker/237a48d87e4d21aea799203b63b12a4f to your computer and use it in GitHub Desktop.
Save kurtdekker/237a48d87e4d21aea799203b63b12a4f to your computer and use it in GitHub Desktop.
Infinite scrolling sprite background in Unity3D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker
// To use:
// import a repeating sprite, FullRect
// drop it on a SpriteRenderer GameObject
// drop this on that same SpriteRenderer you want to be infinitely tiled
//
// Now just move the orthographic camera using the editor Transform controls
public class TiledSpritesInfinite : MonoBehaviour
{
Camera theOrthoCamera;
SpriteRenderer theRenderer;
Sprite theSprite;
float pixelsPerUnity;
Vector2 SpriteSize; // world size of the sprite
void Start()
{
// You may replace this with an explicit reference
// to the camera you want track
theOrthoCamera = Camera.main;
// ensure ortho
theOrthoCamera.orthographic = true;
theRenderer = GetComponent<SpriteRenderer>();
// ensure tiled
theRenderer.drawMode = SpriteDrawMode.Tiled;
theRenderer.tileMode = SpriteTileMode.Continuous;
theSprite = theRenderer.sprite;
// how big is this thing?
pixelsPerUnity = theSprite.pixelsPerUnit;
Rect r = theSprite.rect;
SpriteSize = new Vector2( r.width / pixelsPerUnity, r.height / pixelsPerUnity);
}
void Update()
{
// take current camera position
Vector2 camXYPosition = theOrthoCamera.transform.position;
// quantize by sprite "cells"
int camCellX = (int)(camXYPosition.x / SpriteSize.x);
int camCellY = (int)(camXYPosition.y / SpriteSize.y);
// chunk us along to the proper cell we need to be to stay with camera
transform.position = new Vector3(
camCellX * SpriteSize.x,
camCellY * SpriteSize.y,
transform.position.z);
// adjust our tiled size
float height = theOrthoCamera.orthographicSize * 2;
float width = (Screen.width * height) / Screen.height;
// verge / margin beyond
height += SpriteSize.y * 2;
width += SpriteSize.y * 2;
// drive the size
theRenderer.size = new Vector2( width, height);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment