Select Git revision
BackgroundRoller.cs
BackgroundRoller.cs 2.55 KiB
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BackgroundRoller : MonoBehaviour
{
//rolls with constant speed now, could be adjusted to the movement speed of the platforms or the offset of the player
private Camera camera;
public List<Sprite> bgSprites;
private int currentSprite = 0;
public GameObject currentBackgroundInstance;
public GameObject upcomingBackgroundInstance;
private BoxCollider2D bgCollider;
public GameObject backgroundInstancePrefab;
void Start()
{
camera = Camera.main;
bgCollider = currentBackgroundInstance.GetComponent<BoxCollider2D>();
settUpBackgroundInstance(currentBackgroundInstance);
}
// Update is called once per frame
void Update()
{
Debug.Log("current spire" + currentSprite);
if (currentSprite >= bgSprites.Count - 1)
{
currentSprite = 0; //never do this at home kids
}
//if there are sprites left & we are over half the height, we instantiate another sprite at the top
if (currentSprite < bgSprites.Count - 1 &&
camera.transform.position.y > currentBackgroundInstance.transform.position.y + bgCollider.size.y / 2 - camera.orthographicSize &&
upcomingBackgroundInstance == null)
{
upcomingBackgroundInstance = Instantiate(backgroundInstancePrefab);
settUpBackgroundInstance(upcomingBackgroundInstance);
upcomingBackgroundInstance.transform.position = new Vector3(0, currentBackgroundInstance.transform.position.y + bgCollider.size.y * currentBackgroundInstance.transform.localScale.y, 0.1f);
}
}
public void SetCurrentBgInstance(GameObject bg)
{
currentBackgroundInstance = bg.gameObject;
upcomingBackgroundInstance = null;
bgCollider = bg.GetComponent<BoxCollider2D>();
}
public void settUpBackgroundInstance(GameObject upcomingBackgroundInstance)
{
//https://answers.unity.com/questions/890148/scale-and-place-gameobject-as-a-background-of-the.html
//source
upcomingBackgroundInstance.transform.localScale = new Vector2((Camera.main.orthographicSize * 2 * Screen.width * 0.28f) / Screen.height, Camera.main.orthographicSize * 2 * 0.28f);
upcomingBackgroundInstance.transform.SetParent(transform);
upcomingBackgroundInstance.GetComponent<SpriteRenderer>().sprite = bgSprites[currentSprite];
upcomingBackgroundInstance.GetComponent<BackgroundInstance>().roller = this;
currentSprite++;
}
}