Accelerated Scrolling Background

Hello,
Im trying to create a scrolling background for an infinite runner game with a speed variable that increases over time.

The code so far for the scrolling background is :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackgroundScroller : MonoBehaviour {
    public float scrollSpeed;
    public float targetSpeed =0;
    float speedStepSize = 0.001f;
    public float tileSizeZ;

    private Vector3 startPosition;

    void Start()
    {
        startPosition = transform.position;
    }

    void Update()
    {
        if (targetSpeed < scrollSpeed)
        {
            scrollSpeed = Mathf.Min(scrollSpeed + speedStepSize, targetSpeed);
        }
        float newPosition = Mathf.Repeat(Time.time * (scrollSpeed), tileSizeZ);
        transform.position = startPosition + (Vector3.up * newPosition);
    }
}

The problem with this code is that when the speed changes there is a spike in my game and the speed change of the background is not smooth at all. The code im using to increase the background speed is :

if(bgscroller.scrollSpeed > -5f)
        {
            bgscroller.targetSpeed = -1 - ((score / 5) * 0.1f);
        }

How can i fix that ?
thank you :slight_smile:

1 Like

I need to know about how to fix this too ASAP for my project,

I think your problem is you didn’t multiply the time factor. So in a faster device, speed increases more quickly. You need to multiply time factor anytime you make something move (rotate/scale, basically change) in Update() function.

I think if you change this line =>

scrollSpeed = Mathf.Min(scrollSpeed + speedStepSize, targetSpeed);

into this =>

scrollSpeed = Mathf.Lerp(scrollSpeed, targetSpeed, Time.deltaTime);

it would solve your problem.

1 Like