2D Procedural Level

Hey guys,

I’m working on a 2D game where I want the level to be generated as you go. I have a bunch of level elements that I just want to be spawned one after the other, it should be dead simple. I’ve run into a bit of a problem with something that I thought would work…

I’m using 2 variables, SpawnLocation, and PreviousElementWidth. SpawnLocation’s starting value is 512, I have a bit of ground before I want the random stuff to start. PreviousElementWidth’s starting value is 256.

Here was my logic: I calculate where to spawn the next element by taking the PreviousElementWidth dividing by 2 so I know where it ends, adding this to the element I’m about to spawn’s width divided by 2, and finally adding this to the SpawnLocation. Sadly it does not work, sometimes the elements will overlap, and sometimes there will be gaps between them. The odd thing is if I set my random Integer in Range to 0 - 0, 1 - 1 and so on it works fine, no gaps or overlapping.

My LevelElementsArray is a struct that contains references to my level elements actors and the width of them

  • 0 - 256
  • 1 - 128
  • 2 - 16
  • 3 - 68

Pretend my Random Integer in Range is from 0 to 3
49343-

I went over the math this morning and found out that it was all correct, and then realized it might be because a new random number is generated each time that is called. I ended up fixing it by generating it once, saving it in a variable and then always just pulling from that variable.
49390-

Thaks a lot! Your question and your answer helps me to understand the logic of making procedural levels!