January 27, 2013 · technical gaming projects

a nasty problem cracked

Hurray! After a longish hiatus I’m back with some time to spend on Encounter.

The code I’d rescued from the 90s got me half-way there - by moving circles apart that were intersecting - but didn’t really take care of collisions. If a shot hits an obelisk, it must bounce off at the correct angle. Sounds easy right?

In theory there are some vector formulae you can use to figure out this kind of reflection. That was surprisingly straightforward (or bug-free at least) - I just implemented the formulae with the Vector3 class.

The really tough part is making it all work with the coordinate and rotation system used by three.js. For example, in three.js zero degrees ‘north’ points down the Z axis and not up the X or Y axes. And you absolutely have to get used to thinking in radians. It’s incredibly easy to get confused.

radian compass

My killer bug turned out to be trigonometry. I was struggling with acos/asin to find my angles of collision, which don’t work in 100% of cases. Some hopeful googling pointed me to atan2, which works for all quadrants. A little bit of thinking and rework and all my tests went green.

I could never have fixed this bug without the use of Jasmine. When your brain really starts to hurt, write out some unit tests for all the cases and get them all green. Don’t leave home without Jasmine!

So: the collisions are looking pretty good now. You can bounce your shots intimidatingly back at yourself. There are a couple of cases where a glancing blow doesn’t give the right bounce, but that’s a different problem I already know about. Something for next time : )

Comments powered by Disqus