How to update and render an 2D endless runner that goes bothways

Started by
2 comments, last by danqua 4 years, 6 months ago

I want to make an 2D endless runner, that also allows player to go backwards.

So I have to create random world as the map goes, also keep the old map in case player goes back. I ask about how to update and render this program.

I am thinking having a generate function that takes an x value and generates world from x to (x + chunk size) and when camera reaches x + chunk size, call this function again to generate more map:

function source(x) {
  // generate world for x value
};

And maybe use this function like:

  let worldThings = [];

   // push the world from 0 to chunk size
   worldThings.push(...source(0));

   // called every frame to update world
   function update() {
     if (camera.x > chunkSize) {
       // generate more world
       worldThings.push(...source(chunkSize));
     }
   }

To render these something like:

   // object pooling for rendering things in view
   let renderPool = new Pool();

   function render() {
     // release all objects
     renderPool.releaseAll();

     // take things that are visible
     let renderThings = worldThings.filter(thingsInCameraView);


     // for everything allocate a resource in the render pool
     renderThings.each(renderPool.allocate);

     // render the pool
     renderPool.each(renderThing);
   }
Advertisement

You could make it semi-deterministic and use the x-coordinate as a seed to generate things at that location. That makes it dead easy to jump to any location in the world. Hashing functions can be very useful for randomization here. Pitfall for the Atari encoded 256 screens with a handful of bytes this way.

Another approach could be that you generate the N+1 screen in advance when you reach the N screen with your camera ( + threshhold) and put it right next to the currently drawn screen. Just as @Prototype mentioned, you could store the world information of a screen inside a hash table, this way you could determine an absolute camera offset (index) corresponding to an entry inside the table.

In your update loop you could check if the N+1 screen is already stored, otherwise generate a new one. If the player moves back just use the previous screen (n-1).

| 0 | 1 | .. | camera position (N) | N+1

This topic is closed to new replies.

Advertisement