| Custom timing technique and optimization with setInterval - Custom timing technique and optimization with setInterval |
| Written by Petar Jercic | ||||
Page 2 of 2
How to optimize?Imagine you are making a game with hundreds of objects on stage. You can already see the frame rate dropping. The most expensive action in flash is moving things around every frame. So if we decide which objects are important and which are less important, we are already on our way of optimizing our game. If we separate moving methods from the flash frame rate using setInterval as described before, we can control how often flash updates position of our objects. Less important objects will be updated less frequently than the important ones. Let’s see it on an example. We are going to make a game with four different objects, sun, tree, bush and a beach ball. Sun moves really slowly so we can update his position infrequently, let’s say every second. Tree moves a little bit faster so we update his position more frequently, say five times in a second. Bush is almost in the front, so we update it regularly. And our hero, the beach ball, is updated regularly 30 times in second, because it is the most important object in the game.
This way we saved around 60 expensive function calls in one second. If you place 50 different objects like this on your stage you save 3000 expensive function calls in a second that you can use for something else. Let’s see the code.
Method setInterval as you can see calls moving functions every n specified milliseconds. We define milliseconds as ticks (sunTick, treeTick, shrubTick, heroTick), so for example method “moveTree” will be called every 200 milliseconds that are 5 times in a second (which has 1000 milliseconds). Notice that I calculate not in frame rates but in seconds. Using milliseconds gets easy that way. That’s it. Thanks for reading my tutorial here at ArtCode Games. Comments (0) |