- Home /
Platform Generation For Endless Runner
Alrighty, so, I've got a bit of a problem. I'm trying to make an endless runner (2d) that consists of 5 platforms. The platforms are numbered 0-4 and correspond to their number in the platforms[] array (Platform0 = Platforms[0] and so on). However, I drew the platforms in such as way that each platform can only be next a few of the other platforms (for example, plat0 can only be next to plat1 or plat2). The first code I put below (script that works) was the script without the 'rules' telling which platform could be placed. That script worked fine, unlike the second script posted below that. That script, when run, immediately and continuously spawns platforms at location x =16. (And by the way all platforms are exactly 4 units long which is why in the scripts the platforms are instantiated 4 units further than the last) I hope someone can figure this out!
Thanks!
Script that works: // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); lastPlaced = startPlatform; }
// Update is called once per frame
void Update ()
{
distanceToPlayer = Vector2.Distance(player.transform.position, lastPlaced.transform.position);
platToPlace = platforms[Random.Range(0, platforms.Length)];
if (distanceToPlayer < 8)
{
placed = Instantiate(platToPlace, new Vector2(lastPlaced.transform.position.x + 4, lastPlaced.transform.position.y), lastPlaced.transform.rotation);
lastPlaced = placed;
}
}
}
Script that doesn't work: // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); lastPlaced = startPlatform; }
// Update is called once per frame
void Update ()
{
distanceToPlayer = Vector2.Distance(player.transform.position, lastPlaced.transform.position);
platToPlace = platforms[Random.Range(0, platforms.Length)];
if (lastPlaced = platforms[0])
{
platToPlace = platforms[Random.Range(1,2)];
}
if (lastPlaced = platforms[1])
{
platToPlace = platforms[0];
}
if (lastPlaced = platforms[2])
{
platToPlace = platforms[Random.Range(3,4)];
}
if (lastPlaced = platforms[3])
{
platToPlace = platforms[0];
}
if (lastPlaced = platforms[4])
{
platToPlace = platforms[3];
}
if (distanceToPlayer < 8)
{
lastPlaced = Instantiate(platToPlace, new Vector2(lastPlaced.transform.position.x + 4, lastPlaced.transform.position.y), lastPlaced.transform.rotation);
}
}
}
Answer by loafer · May 16, 2017 at 04:35 PM
There are some syntax errors in your conditionals.
If you are not checking for equality you are setting them equal
if (lastPlaced = platforms[0])
will always be true because you are only using a single equal.
Because you aren't using if / else if every single one of those conditionals will run and you will end up this every single time:
platToPlace = platforms[3];
And then your final conditional will run if distanceToPlayer < 8.
You should use if / else if and also check for equality using
if( lastPlaced == platforms[4] ) { }