[Solved] Keep distance between 2 gameobjects

I have background elements I need to keep a certain distance from the player. As the player moves forward, I need the background elements to stay the same distance away the whole time.

I saw a previous post, but I’m new and I just don’t understand how to keep the two objects apart.

Any help would be appreciated.

Thanks

As NoseKills mentioned, Are you making a 2D or a 3D game? In 3D, you could simply keep the background elements’ position the same to the player. In this script below, gameObjects marked with the tag Background will stay with the player. This may not be the best way, but it works with what information you’ve given:

GameObject[] backgroundObjects;
Vector3 lastPosition;



void Start() {
    backgroundObjects = GameObject.FindGameObjectsWithTag("Background");
}

void Update() {
    foreach(GameObject g in backgroundObjects)
        g.transform.position += (transform.position - lastPosition);

    lastPosition = transform.position;

}

You should place this into a new script that will go on the main Camera. When you run the game, it will set an array of GameObjects to all the GameObjects that are tagged as “Background”. Now this tag isn’t created yet, so you need to go to Edit > Project Settings > Tags and Layers > Tags and create a new tag in the next empty blank called “Background”. Then, in the Hierarchy, find all of your background elements, go to the top, and change the “Tag” to “Background”. When you run the game, it should work the way you want it to.

Thank you for your reply and help. Since I’m new I’ve been pretty much looking for a coding solution to everything. It dawned on me that I simply could parent the background element to the player in the hierarchy to keep the distance.

I’m still going to keep your coding help as a reference, I do appreciate your taking time to assist me.