/*
** Usage:
** distance = range_finder(x, y, dir, range, object);
**
** Arguments:
** x, y position in room
** dir direction to look in degrees
** range the greatest distance to look
** object which objects to look for, or keyword all
**
** Returns:
** distance exact distance to the nearest instance
** of given object in the given direction
** from the given point (x,y), or (-1) if
** no instance is found
**
** Notes:
** Calculates the distance in log2(range) collisions checks.
**
** copyright (c) 2006, John Leffingwell
** www.planetxot.com
*/
var origin_x, origin_y, dir, range, object;
origin_x = argument0;
origin_y = argument1;
dir = argument2;
range = argument3;
object = argument4;
var dest_x, dest_y, shift_x, shift_y, distance;
shift_x = lengthdir_x(range,dir);
shift_y = lengthdir_y(range,dir);
dest_x = origin_x + shift_x;
dest_y = origin_y + shift_y;
if (collision_line(dest_x, dest_y, origin_x, origin_y, object, true, true) < 0) {
distance = -1;
}else{
while ((abs(shift_x) >= 1) || (abs(shift_y) >= 1)) {
if (collision_line(dest_x, dest_y, origin_x, origin_y, object, true, true) < 0) {
origin_x += shift_x;
origin_y += shift_y;
shift_x /= 2;
shift_y /= 2;
dest_x += shift_x;
dest_y += shift_y;
}else{
shift_x /= 2;
shift_y /= 2;
dest_x -= shift_x;
dest_y -= shift_y;
}
}
distance = point_distance(argument0, argument1, dest_x, dest_y);
}
return distance;