- Home /
Spawned Scrolling background objects gaining a gap when speed increases.
Hi everyone!! I am making a game with an infinite background scroller that has an increasing speed. This background is made up of prefab blocks (with scroller spricpts attached) that are consistently instantiated to the right of the camera, such that their edges touch perfectly with no overlap or gap.
These blocks (all the same width) are spawned using a script that spawns a new block whenever the previous block has moved by the width of the block, using the following script:
void Start()
{
lastPosition = meter.transform.position;
}
void Update()
{
meterDistance += Vector3.Distance(meter.transform.position, lastPosition);
lastPosition = meter.transform.position;
if (meterDistance >= 2.9f) //width of the prefab blocks
{
meterDistance = 0f; //reset the "distance meter"
Spawn(); //spawn a new background object
}
}
and these prefab blocks are using a scroller script as follows:
void FixedUpdate()
{
//Scrolls the background (and obstacles) backwards by the scrollspeed. destroys when it gets too far
newPosition = transform.position;
newPosition.x -= PlayerController.scrollspeed;
transform.position = newPosition;
if (transform.position.x <= -20f) Destroy(this.gameObject);
}
And this actually works perfectly; at least when the game begins at a constant scrollspeed.
However, when the scrollspeed increases, the objects start spawning in a lagged fashion: creating gaps in between every block of width proportional to the scrollspeed.
This makes no sense to me, because the spawn time is determined by the DISTANCE traveled, which is definitely proportional to the scrollspeed of that object. So does anyone have any idea why gaps would be appearing?
Thank you so much for your time and help! Zack