# Infinite Parallax Background

Ok, so i have an idea for an infinite parallax background but have no idea how to code it, i’m pretty new to C#, so…

the player has the camera attached to them so as they move, they appear stationary but they are moving through the world. at the start of the level i want it to spawn an object at a random location inside the cameras view port.

i’m actually stuck right here…

``````public float distance;
public float lB;
public float rB;
public float tB;
public float bB;
public float randomX;
public float randomY;

// Update is called once per frame
void Update ()
{
distance = (transform.position - Camera.main.transform.position).z;

randomX = Random.Range (-10, 10);
randomY = Random.Range (-6, 6);

lB = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, distance)).x;
rB = Camera.main.ViewportToWorldPoint (new Vector3 (1, 0, distance)).x;

bB = Camera.main.ViewportToWorldPoint (new Vector3 (0, 0, distance)).y;
tB = Camera.main.ViewportToWorldPoint (new Vector3 (0, 1, distance)).y;

if (bB == 0)
{
transform.position = new Vector3 (randomX, tB, -20);
}
else if (tB == 0)
{
transform.position = new Vector3 (randomX,bB,-20);
}
}
``````

from what i understand, the if statement is the problem, its not executing the transform.position.

I haven’t even gotten to making a few hundred of these stars appear and all execute this code.

I don’t understand how this code is giving you a random position within the camera view. Here are a couple of points:

• Never directly compare two floating point values…especially if one is the result of any kind of calculation. You can use Mathf.Approximately() to compare them.
• Not sure it makes in difference, but the integer version of Random.Range() is exclusive of the upper value. So for example RandomX will get values from -10 to 9, and only integer values. I think you want this instead: `randomX = Random.Range(-10.0f, 10f);`

Now if you are trying to produce random positions in the view of the camera at ‘distance’ from the camera, you can use these two lines:

``````Vector3 pos = new Vector3(Random.Range(0.0, 1.0), Random.Range(0.0, 1.0), distance);
transform.position = Camera.main.ViewporToWorldPoint(pos);
``````

Wow, thank you so much, I’ve been struggling with this all day, haha, i cant believe i overlooked something so simple, it works like a charm, although the sprites clump up when i travel in both the X and Y directions at the same time but i can live with that for now.