- Home /
I'm making 2d game and I want to change background which will last for some random time and it will also appear in random time.
So in game I made background of 2 same images which moves upward (character looks like he is falling down even though he is standing still) and I made that by putting hight limit and when the 1st image reaches it it will appear under second one and when second one reaches limit it will appear under first one and so on. Now I want to insert alternative background which will randomly appear for example between 20 - 40 seconds after starting of game and it will last 15 - 30 second and after that I want again to move on the first background and alternative will appear again after specific time... Thanks a lot in advance! ;) Here is my code for that and only appearing of alternative background is not working:
using UnityEngine; using System.Collections;
public class BackgroundMovement : MonoBehaviour {
private float Limit; // hight limit
private float TileHeight; // hight of one picture
public float MovementSpeed; // speed
float theTime;
public Sprite normalBack; //first background
public Sprite altBack; //alternative background
Sprite Background;
bool isNormal;
bool changeBack;
// Use this for initialization
void Start ()
{
Limit = 15f;
TileHeight = 18f;
changeBack = false;
isNormal = true;
Background = normalBack;
theTime = 0;
}
// Update is called once per frame
void Update ()
{
if (Time.time - theTime > 40-20)
{
theTime = Time.time;
changeBack = true;
if (!isNormal)
Background = normalBack;
else
Background = altBack;
isNormal = !isNormal;
}
Vector3 position;
for (int i=0; i<this.transform.childCount; i++)
{
position = this.transform.GetChild(i).transform.localPosition;
position.y += MovementSpeed * Globals.movementSpeed * Time.deltaTime;
if (position.y > Limit)
{
position.y = position.y - (TileHeight * this.transform.childCount);
position.y -= TileHeight * 2;
if (changeBack)
{
this.transform.GetChild(i).GetComponent<SpriteRenderer>().sprite = Background;
}
}
this.transform.GetChild(i).transform.localPosition = position;
}
changeBack = false;
}
}