I’ve made an improved version of my 2D AI Targeting demo for Game Maker. My original AI Targeting was limited by the fact that an object could not target other instances of the same object type — doing so in effect would cause the seeker object to attempt to target itself.
The original AI Targeting routine used
instance_nearest(), which works great if you are targeting an object of a different type. If you need to target the same type of object, however,
instance_nearest() won’t help you, since the nearest instance of the same object is always
Using instance_nearest_extended by Kyle_Solo, I was able to come up with a routine that allows for “cannibal” AI targeting — that is, targeting an object of the same type as the seeker.
I struggled for a long time to use the
instance_xth_nearest() method to accomplish cannibal targeting, which seemed to be suitable as it has a built-in criteria test, but was unable to get the function to work as desired. I’m still not entirely sure why, but I am guessing that it may be due to the “
other” keyword being undefined or referencing “
noone” when an object is not involved in a collision.
I ended up successfully completing the project using
instance_nth_nearest and a bit of extra code which performed the criteria testing that I required. In order to get my testing code to work, I had to introduce a global variable to count the number of instances of the targeted object, so I could construct a loop to iterate over them using instance_xth_nearest(). I’m wondering if there isn’t a faster or more graceful way to accomplish this, but it works well for now.
In the video above, the Arrows target the nearest Arrow that is small enough for them to “beat”. The rule I am using here is that a bigger arrow must be 1.3x the size of a smaller arrow in order to be able to “beat” it, but this could be modified to some other condition by changing the
can_beat() function. If a candidate target cannot be “beaten” the arrow considers the next nearest arrow, and so on, until all of the instances of the targeted object type have been checked. If no arrow is small enough to be “beaten”, the arrow flies in a straight direction.
Source .gml and a demo .gmk project is available at the Releases page; a .gex extension build will be released in the near future.