instance_nearest always returns id -4 [Solved]

murchie85

Member
[solved] I am still unsure of what the id = -4 refers too, but I was able to simplify the code by simply not using the instance_find in the iinstance_nearest function.


In my code I am trying to get the distance to the nearest enemy, turn and shoot. However the function instance_nearest appears to only return -4 id even when room is full of enemies. Ive done some googling, but can't find if -4 refers to noone?
I have debugged all other variables to make sure nothing wrong along the way as such:

- instance_number(oFParentEnemy) works fine returns the numbers of enemies in the room
- instance_find(oFParentEnemy, i) works fine, when printed to screen its a list of IDs like 11001.. blah (no -4's)


GML:
// ------------SHOOT NEAREST IF IN SIGHT
var _lineOfSight = global.cameraWidth;
for(var i = 0; i < instance_number(oFParentEnemy); i += 1){
var nearest = instance_nearest(x, y, instance_find(oFParentEnemy, i)); // Offending line, returns -4 regardless of situation.


if (distance_to_object(nearest) <= _lineOfSight)
{
    // -------- TURN TO ENEMY CODE

    // --------- FIRE CODE


}
}

 
Last edited:

Roldy

Member
(-4) is the value of the built in keyword noone.

instance_nearest wants an object_index not an instance id.

I believe you are confused in general about how it works. The for loop in your code is pointless.

GML:
// ------------SHOOT NEAREST IF IN SIGHT
var _lineOfSight = global.cameraWidth;

// This loop is pointless
// instance_nearest will already do a loop of all oFParentEnemy instances
//for(var i = 0; i < instance_number(oFParentEnemy); i += 1){

    // This line is incorect
    //var nearest = instance_nearest(x, y, instance_find(oFParentEnemy, i));

    // what you want is probably just the following
    var nearest = instance_nearest(x, y, oFParentEnemy);

    if (nearest != noone && distance_to_object(nearest) <= _lineOfSight)

    {
        // -------- TURN TO ENEMY CODE
        // --------- FIRE CODE
    }

//}
 
Top