Last month, I started researching LibGDX, a game engine mainly targeted for Android. Also, this was the first time I worked with a game engine.
My goal is to develop a platform game like Vector but much simpler. This is also inspired by Temple Run. The main character keeps running and avoid being chased by the NPC. Precisely, I have to say that the main character just stays at one place and the background keeps moving backward.
The first problem that I encounterd was the infinite scrolling background. I have researched through Google with many solutions. However, all of them are too complex to solve that simple task. The code can be up to 100 lines long with tons of complicated mathematical formula to calculate how to scroll the background. Finally, I gave up and decided to come up with my own solution. Amazingly, it took me only less than 15 minutes and about 10 lines of code to achieve it.
The theory is very simple. Assume that you have a background file names bg.jpg, what you have to do now is to draw that background, move and loop it side by side. Let's look at the image below and I'll explain
Actually, what we have to do it is just move the separator and draw 2 background image on two sides of it. When the separator reach the screen edge, move it back to the other screen edge and then continue all the previous steps.
Let's look at the video of this very simple example (sorry for the bad video quality).
Here is the code which I implemented using LibGdx. For other engine, it would be similar, the same theory, just different implementation. The demo code below is very dirty, so don't use it in the production.
First, declare a the background texture and the camera. The currentBgX is the current X position on the co-ordinate of the separator. lastTimeBg is used for determine the time between each time the background move. In the create() method, init those variable In the render() function, draw the background on both sides of the sepearator between the batch.begin() and batch.end() block Also, in the render() method, we need to move the separator You can download the source here After downloading, import those 4 projects into Eclipse. Depending on your preference, you can run the project as an Android app, Desktop app or HTML5 app.