VBfx / Tile tutorial / Step 1

Introduction

Of course the engine isn't fully working yet. There's quite an important part missing that covers units, the player, animals and other things that might appear in your game: moving objects. There are two ways to make sprites move in a tile engine: tile-based and pixel-based. This may sound like the same problem we already had when moving the camera, well it's similar but it's not.

Mapping objects

Instead of just adding another layer that holds the objects we only need a map here that points to the objects. It's quite the same as we did with the tiles, except that object positions aren't bound to the map. Let me try to explain the idea.

In the tile map array we used the array index to calculate the tile's position on the screen (see Draw function). Now objects can freely move around and therefore we can't just put them in a map as we did with the tiles (well it's possible but compicated and a pure waste of memory).

So why don't we just use simple array that holds all objects in the map, where each object has it's own coordinates? Objects could move around freely and we'd just have to subtract the camera position (which is already in pixels) to get the screen-position. But what about collisions? Since any object could be anywhere we'd have to compare the position of every object to each other's and this would kill our engine for sure! Using a little math you can calculate the number of checks, it's i * (i + 1) / 2 where i is the number of objects. So 100 objects would already result in 5050 collision checks!

Blocked tiles are marked red

The way to go is a combination of both techniques. We use a array to hold all the objects and another map layer that only holds the object indices. You can think of the objects being registered to this map.

Now imagine again 100 objects but now they are registered to the map. When checking for collisions we can just look-up on the map (we get the map index from the object's position) if there's a object registered or not. If any object is on this tile it will contain it's index. And that's it already, instead of 5050 we now have 100 checks to perform.

If you still don't get it just keep on reading, we'll get back to this later when doing collisions.

Collision grid

Of course this way of collision isn't that good. The collision grid you get is quite large, actually we're using the same size as the tiles are. But you can still use this technique to know if two objects are even near each other. If so you can apply another (more complex) collision code, if not you can just skip the objects to save performance.

Conclusion

Moving objects aren't that easy to handle because they can move around freely. To speed up collision checks we'll a additional look-up map that only contains indices of the corresponding objects. Therefore collisions will be tile-based but for the moment this is good enough.

Navigation