Lets Build Community

Lets Build is a community of 163 amazing members

We're a place where indie game developers to connect with one another to share ideas, ask for help and teach each other.

Create new account Log in
loading...
Cover image for Moving 2D Backgrounds in Unity

Moving 2D Backgrounds in Unity

gamedev4k profile image Game Dev 4K ・1 min read

In my Unity 2D Game, I need to move some items in the background, including:

  • Pavement
  • Street Lights
  • Buildings

Then it feels like the player is moving. But actually, the items are moving backward.

Have a look at this video:

It'd be great if we automatically spawn these items & move. That's where we can get some help from a C# script. Here's how to do that:

  • Create a script called "InfiniteMovingBelt.cs" in your project
  • Then add the following content
  • Then Create an "Empty Game Object" and add this script

After that, customize the parameters of this script as shown in the above video.

Better Solution?

Since this might be a common task in 2D games, I think there is a much better solution than this. If you know a better solution, just let me know.

Discussion

pic
Editor guide
Collapse
rcarlson profile image
Robert Carlson

This is very similar to an approach taken by @cpluta . I like how re-usable this code is! Nice work :)

Collapse
gamedev4k profile image
Game Dev 4K Author

Thanks. I'll have a look at this tut as well.

Collapse
cpluta profile image
Chris Pluta

Looking at what you did and I came up with it's super similar!

The biggest difference is I have a game manager taking care of the speed of the scene. I also chose to attach the script to every prefab that is "scrollable".

I can definitely post a more detailed article if you'd like to know more.

Below is how I have it configured with the script.

Cannon Toss - Propel Ball Game Object Components

public class BallMoving : MonoBehaviour
{
    private GameManager gameManager;
    // Start is called before the first frame update
    void Start()
    {
        gameManager = GameObject.FindGameObjectWithTag(GameManager.GameManagerTag).GetComponent<GameManager>();
    }

    // Update is called once per frame
    void Update()
    {
        var position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z);

        position.x = position.x - (gameManager.ballXVelocity * Time.deltaTime);

        this.transform.position = position;
    }
}
Thread Thread
gamedev4k profile image
Game Dev 4K Author

Thanks for the update.
Yeah! I got how it works.

This is handy: GameObject.FindGameObjectWithTag. I didn't know about this API.

Thread Thread
cpluta profile image
Chris Pluta

This script is being created as part of a prefab, and I wasn't sure how to get a reference to this specific component.

I could have made a singleton, but I live by friends don't let friends singleton. 😆