Thursday, September 26, 2013

seeker and you shall finder

Something I had to look up "how did I do that again?" in my little toy/gamemaking: have an object that will gradually turn to a target.

I made a really pretty version of this in an art game called aRTSeroids which I cribbed for this entry...

It's easy enough to get a seeker to snap instantly to its target, just do atan2(deltaY,deltaX); -- figuring out "which direction should I turn to get my angle closer to it" is a little tricker.

You can see the source here. The seeker object has an x and y propery for its position on the screen, and then an a property with its current angle. It also has a MAXTURN that sets how far it can turn per click...

The first trick is the "deal with the overlap". This is optional, but nice for games that feature screen wraparound-- (i.e. fly left, show up right)-- if you want to have definitive borders you can leave those lines out.

The next bit is just the hack I got to normalize the difference in the angle... esentially we try to make sure the difference between the angle it "wants" and where it is now is normalized between PI and -PI.

Finally, that smaller() code says it will either go MAXTURN or the difference in the angle. If it just went MAXTURN, it sometimes will do a little vibrate pattern as it overshoots the angle. (Come to think of it, I think that vibration is why I did that "arbitrary value to ignore")

Anyway, the code is a little clunky and weird but it works well, and should be useful to me in future projects.