# Infinite sidescrolling terrain in Unity

I am trying to create a horizontal line at the center of the screen that goes infinitely. I could make the line short and move it with the camera but the shape of my line actually changes as you progress. I am using a line renderer and I am not sure what is the best way to achieve this?

Secondly, the camera keeps moving to the right so I would like those parts of the line that are not visible anymore to get destroyed. I am also not sure how to achieve this since this is one big line I assume?

• Can you be more precise? What does your line look like? What's its displacement? What have you tried so far? – liggiorgio Apr 3 '18 at 9:24

Keep a fixed-size array of line segments wide enough to accommodate your camera at max zoom. These are fed into your LineRenderer via .SetPositions().

struct LineSegment
{
Vector2 p0;
Vector2 p1; //this will be the same as p0 of the next segment
Color color;
//etc.
}

LineSegment[] lineSegments = new LineSegment[SIZE];


As you move right, you need to get the appropriate LineSegment inserted to the start or end of the array (depending on which way you are moving) and shift out old ones (leftmost):

//MOVE RIGHT
void MoveCameraRight()
{
lineSegments[0] = null; //remove leftmost (you don't actually need this line)

//shift all 1 segments to the left
for (int i = 1; i < lineSegments.length; i++)
{
lineSegments[i - 1] = lineSegments[i];
}

//get the new rightmost segment
lineSegments[lineSegments.length - 1] = RetrieveLineSegmentAt(i);
}

//move left - I'll leave this one to you! very similar.

void RetrieveLineSegmentAt(int i)
{
//generate procedurally
//OR
//retrieve from some larger list, database, or whatever.
}


If you ensure that your line segments are always the same width in x (even if tilted), you will always know exactly how many elements you need to fill the screen. I'd recommend this - it's easier. If, however, the rotation of individual line segment causes some to be narrower than others, like so:

    |\_
/   \_
|      \_
/         \_
|            \_
^             ^
5 wide        10 wide


...then you will have to dynamically calculate how many you will need to fill the screen.

I would implement the whole terrain as a 1D heightmap, that is, just a sequence of heights at each evenly-spaced point. Your screen's lineSegments array can then be populated from the heightmap. This also means you can avoid dynamic width calculation, keeping things simple.