Skip to content

Instantly share code, notes, and snippets.

@CamdenSegal
Last active December 31, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CamdenSegal/7919096 to your computer and use it in GitHub Desktop.
Save CamdenSegal/7919096 to your computer and use it in GitHub Desktop.
Unity 4.3 Parallax script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Parallax : MonoBehaviour {
// Scale of movement 0 being stationary 1 being sticking to the camera.
public Vector2 parallaxScale = new Vector2( 0.5f, 0.2f );
// Do child elements loop?
public bool looping;
private List<Transform> loopElements = new List<Transform>();
private Vector3 prevCameraPos;
void Start () {
if ( looping ) {
for ( int i = 0; i < transform.childCount; i++ ) {
Transform child = transform.GetChild(i);
// Add only the visible children
if ( child.renderer != null ) {
loopElements.Add(child);
}
loopElements = loopElements.OrderBy(
t => t.position.x
).ToList();
}
}
prevCameraPos = Camera.main.transform.position;
}
void Update () {
Vector3 posDiff = Camera.main.transform.position - prevCameraPos;
posDiff.x = posDiff.x * parallaxScale.x;
posDiff.y = posDiff.y * parallaxScale.y;
transform.position += posDiff;
if ( looping ) {
Transform possibleFlipper;
if ( posDiff.x > 0 ) {
// Moving forwards
possibleFlipper = loopElements.FirstOrDefault();
if ( possibleFlipper.renderer.IsVisibleFrom( Camera.main ) == false ) {
// Flip it!
Transform otherEnd = loopElements.LastOrDefault();
possibleFlipper.position = new Vector3( otherEnd.position.x + otherEnd.renderer.bounds.size.x, possibleFlipper.position.y, possibleFlipper.position.z );
loopElements.Remove( possibleFlipper );
loopElements.Add( possibleFlipper );
}
} else {
// Moving backwards
possibleFlipper = loopElements.LastOrDefault();
if ( possibleFlipper.renderer.IsVisibleFrom( Camera.main ) == false ) {
// Flip it!
Transform otherEnd = loopElements.FirstOrDefault();
possibleFlipper.position = new Vector3( otherEnd.position.x - otherEnd.renderer.bounds.size.x, possibleFlipper.position.y, possibleFlipper.position.z );
loopElements.Remove( possibleFlipper );
loopElements.Insert( 0, possibleFlipper );
}
}
}
prevCameraPos = Camera.main.transform.position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment