Tile-based algorithm is one of the method to optimize the game. How to say? Because it reduces a lot of unnecessary calculations and increases the game performance.
Many loops of a block of codes slow down the game progress especially doing the complicated calculation for many times. The way to prevent from lagging is reducing the number of loops. So, how to reduce? Tile-based algorithm can solve this problem.
Although by using this method I have to do more works but it can greatly improve the game performance to run smoothly. Firstly, I create a 3-dimensional array. What is the usage of this array? It is used to track the location of every object.
3D Array Structure
Main Array = Rows Array
Each item in Rows Array = Columns Array
Each item in Columns Array = Object Container (Array)

In my game, the world is divided into tiles. Each tile is fixed at the specific area. The "Free Runner" locates in the area of tile (1,2) on the map. Therefore, this object is added into the container in Array[1][2]. When it moves into the area of tile (1,3), it will be removed from the container in Array[1][2] and added into Array[1][3] to update its latest location.

Welcome to my another guest - Missile Launcher (ML)! The red circle around it indicates its attack range. How to get the purple area? Let's say the size for every tile is 100 x 100 unit2 and the attack range of the ML is 80 units. Round up ( 80 / 100 ) is 1. So, the purple area only includes the tile that is 1 unit distance away from ML's location which is (3,3).
There are 4 ships with A, B, C, D in the picture. Ship A can be ignored because it is out of the purple area. Ship B, C, and D become the candidates in checking to see which one is inside the area and become one of ML's attack targets. Congratulate to Ship C that it becomes ML's attack target. Because the distance between it and ML is shorter than ML's attack range, it means the ML is able to attack it.
By using this method, I calculates the distance between the ML and each of the 3 objects only instead of 4 objects in the world. In the other words, if the world has 50 objects and there are only 3 objects inside the purple area. I just need to take the 3 objects to do calculation in 3 loops. I can reduce the time for doing 47 loops. But it increases the work for another part. Whenever any object moves from one tile to another tile, it should update the 3D array by removing the object from its old location and adding into new location.
p/s:
I would like to greatly appreciate the God of Programming - Solid X - a.k.a Acefreakz in giving me the idea of this algorithm. His great idea helps me a lot in optimizing the calculation and game performance. Thanks him very much!
wei, u din gif me credit on this de? LOL 忘恩负义的小孩子~!
ReplyDelete