deltaDir()

by Crazy Star


Posted on October 08, 2005 at 7:53 PM



This demonstrates a script I made. It's probably the script I use the most so I thought I'd share it..

It takes two arguments and returns the difference between them in degrees. Eg.
deltaDir(30,120) returns 90 and deltaDir(10,270) returns -100.

I also added some functions that although similar has their own use.

<b>update</b>

Added a ton of comments! I hope this will make someone =)



RPR commented May 15, 2006 at 12:10 PM
This piece of code seems to be the one to use with homing missiles, a.i. cars and enemies etc. I rely on Spectre and trust it works.

But the example is too complicated. First of all, it has two scripts to deal with the main purpose. Here's a neat edit:

// deltaDir(current degrees, aiming degrees)
{
var a, b, c;

a = argument0;
b = argument1;

while(a >= 360 || a < 0) a -= 360 * sign(a);
while(b >= 360 || b < 0) b -= 360 * sign(a);

c = (a - b);

if(c > 180 || c < -180) c -= 360 * sign(c);

return c;
}

Let's say you have a car driving around a track and heading for a point set somewhere close to the next curve. You give the current direction of the car and the direction to the point (car.dir, point_direction(car.x, car.y, px, py)).

If the car is not already heading for the point, it turns. The easiest way to deal here, is to set the car turn one degree clockwise if the delta is positive and counter-clockwise when it's negative.

A more advanced way is to turn the car more when the delta is higher. Anyway, because GM already gives the fixed degrees in point_direction(), you won't even need more than a couple of lines:

c = car.direction - point_direction(car.x, car.y, px, py);
if(c > 180 || c < -180) c -= 360 * sign(c);

d = // how much the car will turn, may depend on c
car.direction += d * sign(c);

Hope this works.
noshenim commented June 03, 2006 at 10:13 PM
heh, nice tunnel
Zac1790 commented December 02, 2007 at 8:07 PM
Yes I made a script for the same purpose a long time ago when I first realized that it was a mathematical exception for a variable to go to 0 again after 359. This script is of course better though :P
noshenim commented July 19, 2008 at 5:10 AM
Used it in my top-down portal game, helpfull and usefull, 10/10