Create an infinite scrolling world with Starling and Nape

Many of you have probably used Box2D to make physic games, although for a few years I have been using Nape.

Nape Physic

Nape is much faster and optimized than Box2D, and finally has an API that makes sense.

It is also updated frequently and the author, Luca Deltodesco, is a great guy.

In this tutorial I want to show you how easy it is to create an infinite scrolling physic world using Nape and Starling, so you can not only leverage the speed of Stage3D, but also the amazing performance of this physic engine.

This is what the final result will look like (click to play it):

In this example the camera is fixed on the Player and the terrain is made of slices.
You can change the width of the slices, if you leave it at around 30 it looks pretty good.
The hills are created with a Math.sin algorithm.

OK, getting to the code:

The Document Class

This class is very simple and it is needed to initialize Starling.

World Platform

In this class we initialize the Nape Space and set the method createSlice() which will generate a new slice of terrain every time a slice gets destroyed.
The method checkHills() actually verify that every slice is visible, if not it destroys it and creates a new one.
Also the panForeground() is the function that fix the camera on the Player.
The Matrix is used to skew the terrain image so that the vertexTopRight matches the vertexTopLeft of next slice.

Player Class

This class creates a Player body, also since the nature of this example is to provide a left to right acceleration I set a minimum velocity of 350 in the onCharacterUpdate.
There is a listener for Touch (Clicks on Starling are always Touch) so that when you click the screen the Player jumps.

I know it is a lot of code but believe me, it has been highly optimized.
Write me a message if you have any question.

I hope you enjoy :)

13 thoughts on “Create an infinite scrolling world with Starling and Nape

Leave a comment

Your email address will not be published. Required fields are marked *