Optimization

The fifth level is finally finished!!

Man it feels good to have that one behind me. It only took five friggin’ weeks to get it up to snuff. Once it was done, I celebrated by just playing MGS for a few days, because I’m a hopeless fanboy and I needed a break. But you’re not here to read about me playing MGS, so let’s talk a little about optimization.

There’s one area of the fifth level that can have a loooot of baddies on screen — like, 100 at once if you let things get out of hand. Enemies don’t usually collide with each other, so normally it wouldn’t be worth mentioning, but these enemies get in each other’s way and so they all have to collision-detect each other, which can get ugly fast.

If you didn’t read last week’s blog: it takes 4 calculations to see if two entities touch. If you add up the calculations of 100 entities checking each other, it’s something around 40,000 calculations (every 1/60th of a second!) and that can really slow a machine down. That’s when optimization is needed!

We’ve seen that in code, entities are rectangles — the four calculations compare the four sides against each other. But if you add another calculation before those — one that treats the entities as circles instead of squares — it cuts down the overall calculations immensely.

Creating a circle from an entity’s rectangular hitbox.

It only takes 1 calculation to see if two circles touch (if the distance between two circles is greater than the sum of their radiuses, they aren’t touching.) This lets you decide if it’s even worth doing the other 4 calculations — if the entities’ circles don’t touch, then their rectangles won’t either!

See? If the distance between the circles is greater than their added radiuses, there’s no way they touch.

Worst case, the entities are touching, so you’ve made the computer do 5 calculations instead of 4. But in most cases it’s only had to do 1, and you’ve cut the work down to 1/4th of what it used to be!

There’s tons of other ways to optimize games, but I won’t get into them now. MGS ain’t gonna play itself! I promise lots of moving, colourful pictures next week. I pinky-swear.