Hello,
I am trying to make a scrolling background for a 2D shooter and would like to have a first background image, once the top of it is about to be on screen load up a second background image so on and so forth.
I have been pulling my hair out trying to get this to work but can’t seem to make anything happen…
Here is my current code, what is now happening is that the second background image will spawn correctly but then the 3rd and so forth will start moving towards the bottom of the screen spawning another one after another one.
Any help or technique ideas is appreciated
thanks in advanced,
Quentin
PS: This is javascript
var movementSpeed;
var nextBG: GameObject;
private var objectAlreadySpawned : boolean;
function Awake () {
objectAlreadySpawned = false;
}
function Update () {
transform.position.z -= 0.05;
if(!objectAlreadySpawned)
{
if(renderer.bounds.min.z < -15)
{
print("transform.position.z is " + transform.position.z);
Instantiate(nextBG, Vector3(transform.position.x + 0.38, transform.position.y, transform.position.z + renderer.bounds.size.z*1.51), transform.rotation );
objectAlreadySpawned = true;
}
}
//print(renderer.bounds.min.z);
}
Here’s something I was mucking around with a few days ago that might help out. This code isn’t particularly good in itself, but it might give you some ideas:
using System.Collections.Generic;
using UnityEngine;
public class BackgroundSpaceAnimation : MonoBehaviour
{
public List<Material> Materials = new List<Material>();
public float rotationSpeed = 10.0F;
private int materialIndex = 0;
void Start()
{
gameObject.renderer.material = Materials[materialIndex];
}
void Update()
{
float offset = Time.time * (rotationSpeed / 1000);
gameObject.renderer.material.mainTextureOffset = new Vector2(0, offset);
if (offset > 1) offset -= 1;
}
void NextTexture()
{
if (materialIndex == (Materials.Count - 1))
{
materialIndex = 0;
}
else
{
materialIndex++;
}
gameObject.renderer.material = Materials[materialIndex];
}
}
thanks for the quick reply, the code is indeed attached to the next background object. So in your code your essentially just switching the material of the object?? I am going to look into doing that but I feel that it may not be smooth, thanks for the help!
Thank you so much for your code!
I converted it to javascript and messed around with it.
It works well expect the material gets completely replaced, so it is a bit of a shock as the images don’t just come one after the other… which is the desired effect I would like.
I shall mess around with it some more and see what I can come up with,
thanks again,
Quentin