P
Prometheus1998_
Guest
I'm trying to create a script that returns the nearest instance in 3-dimensional space, by looping through all active instances of the object, evaluating the distance using the built-in function "point_distance_3d", sorting the ds_grid containing the data so that the smallest distance value is in the [0,1] position, and returning the id saved in the [0,0] position.
For ease of testing, I've been using a flat plane, assuming all objects are on the same z-level (z = 0).
The grid I have been using to test has nine objects, arranged like so:
| a b c |
| d e f |
| g h i |
The object running the test starts in the "e" position, but indicates the closest object it tests for is in the "i" position. In addition, despite running in the "Step" event, it only calculates the nearest object once. It behaves exactly the same if I change the "ascending" parameter for ds_grid_sort from true to false.
Replacing the script in the spoiler tags above with the built-in function "instance_nearest" functions exactly the way it should, so I'm reasonably confident the problem is in the ds_grid, either saving the data or sorting it. Given the way it (doesn't) change behavior when switching how it sorts the information in the grid, I'm pretty sure I messed up the sorting. I just can't figure out how, and would appreciate any help that can be provided.
Code:
///instance_nearest_3d(x,y,z,obj)
object = argument3;
arg_x = argument0;
arg_y = argument1;
arg_z = argument2;
var instances = ds_grid_create(instance_number( object ),1);
for(var i = 0; i < instance_number( object ); i += 1) {
var inst = instance_find( object , i);
var dist = point_distance_3d(inst.x,inst.y,inst.z, arg_x , arg_y , arg_z )
ds_grid_add(instances,0,i,inst.id);
ds_grid_add(instances,1,i,dist);
}
ds_grid_sort(instances,1,true);
var val = ds_grid_get(instances,0,0);
ds_grid_destroy(instances);
return val;
For ease of testing, I've been using a flat plane, assuming all objects are on the same z-level (z = 0).
The grid I have been using to test has nine objects, arranged like so:
| a b c |
| d e f |
| g h i |
The object running the test starts in the "e" position, but indicates the closest object it tests for is in the "i" position. In addition, despite running in the "Step" event, it only calculates the nearest object once. It behaves exactly the same if I change the "ascending" parameter for ds_grid_sort from true to false.
Replacing the script in the spoiler tags above with the built-in function "instance_nearest" functions exactly the way it should, so I'm reasonably confident the problem is in the ds_grid, either saving the data or sorting it. Given the way it (doesn't) change behavior when switching how it sorts the information in the grid, I'm pretty sure I messed up the sorting. I just can't figure out how, and would appreciate any help that can be provided.