Skip to content

Instantly share code, notes, and snippets.

@yanniboi
Created April 16, 2021 09:24
Show Gist options
  • Save yanniboi/6b9c0012c3162c6eaf4cc8827994f444 to your computer and use it in GitHub Desktop.
Save yanniboi/6b9c0012c3162c6eaf4cc8827994f444 to your computer and use it in GitHub Desktop.
Parallax background script (by codemonkey)
using UnityEngine;
public class ParallaxBackground : MonoBehaviour {
[SerializeField] private Vector2 parallaxEffectMultiplier;
[SerializeField] private bool infiniteHorizontal;
[SerializeField] private bool infiniteVertical;
private Transform cameraTransform;
private Vector3 lastCameraPosition;
private float spriteWidth;
private float spriteHeight;
private void Start() {
cameraTransform = Camera.main.transform;
lastCameraPosition = cameraTransform.position;
Sprite sprite = GetComponent<SpriteRenderer>().sprite;
Texture2D texture = sprite.texture;
spriteWidth = texture.width / sprite.pixelsPerUnit;
spriteHeight = texture.height / sprite.pixelsPerUnit;
}
private void LateUpdate() {
MoveBackgroundRelativeToCamera();
if (infiniteHorizontal)
{
if (CameraPassedEdgeOfSpriteX) {
float howFarToMoveCameraX = DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundX % spriteWidth;
transform.position = new Vector3(cameraTransform.position.x + howFarToMoveCameraX, transform.position.y);
}
}
if (infiniteVertical) {
if (CameraPassedEdgeOfSpriteY) {
float howFarToMoveCameraY = DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundY % spriteHeight;
transform.position = new Vector3(transform.position.x, cameraTransform.position.y + howFarToMoveCameraY);
}
}
}
private void MoveBackgroundRelativeToCamera()
{
Vector3 currentCameraPosition = cameraTransform.position;
Vector3 amountCameraMovedSinceLastFrame = currentCameraPosition - lastCameraPosition;
transform.position += new Vector3(amountCameraMovedSinceLastFrame.x * parallaxEffectMultiplier.x, amountCameraMovedSinceLastFrame.y * parallaxEffectMultiplier.y);
lastCameraPosition = currentCameraPosition;
}
// Code cleanup.
private float DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundX => cameraTransform.position.x - transform.position.x;
private float DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundY => cameraTransform.position.y - transform.position.y;
private bool CameraPassedEdgeOfSpriteX =>
(Mathf.Abs(DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundX) >= spriteWidth);
private bool CameraPassedEdgeOfSpriteY =>
(Mathf.Abs(DistanceBetweenMiddleOfCameraAndMiddleOfBackgroundY) >= spriteHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment