Programming Tip #1

All right, I’ve decided to start making a few tips for new programmers as I, myself, learn to program, in the hopes it may help anyone new to programming, and game making specifically.

So, today’s random tip is Floor, and not the kind you stand on, mind you! No, this floor is a special function that allows you to round any number down to the last whole integer. Seems pretty simple you say, huh? Well, it is! It also has a very useful purpose, and that is grid based positioning.

For instance, say you have an object that is moving around the screen, but you want it to collide with a grid. This is very simple with your friend, the floor method. If  you have an object that is at (19,32) and your game is a 4×4 grid of 32×32 tiles, you may want to know where it is in the grid. Assuming most objects aren’t a single point, the easiest way to do this is to get the floor position of each corner of a sprite, for a rectangular or square object. If you were to round here, a point that is 9/10ths of the way into a tile becomes in that tile, when it really hasn’t collided yet. That’s why floor is useful!

A simple collision test for an object whose speed never exceeds the size of a tile, so for instance, an object moving 4 pixels per frame with 32×32 pixel size tiles, is simple with floor. Just by doing a nested if loop you can achieve a decent collision tests. Also, you will want to check the four corners for collision, taking into account their next position based on current speeds, and if collides, stop it before it intersects the grid.

This is just a VERY remedial collision method, but it does work for simple collisions. If I’ve made any mistakes, please comment below so I can correct them!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s