GameMaker: ‘strategy’ unit selection

Today I've made a simple example for strategy-like unit selection.
That is, selecting units (instances) with mouse, with selection rectangle and selected units being displayed accordingly.
Example is well-commented and should be easy to use.
Principle of work is simple - to detect units that overlap selection rectangle, game should cycle through them, performing collision_rectangle checks. Amount of calculations and code complexity is cut here by local variable usage (if you did not know, local variables 'var' will be available inside of with constructions without any prefixes).

Download GMK

Source code follows,

var x1, y1, x2, y2, n;
// detect selection rectangle bounds:
x1 = min(select_x1, select_x2);
y1 = min(select_y1, select_y2);
x2 = max(select_x1, select_x2);
y2 = max(select_y1, select_y2);
// number of units found:
n = 0;
unit = 0; // reset the unit-array
with (obj_unit) {
    if (collision_rectangle(x1, y1, x2, y2, id, false, false)) {
        other.unit[n] = id; // store unit id in obj_select list
        n += 1; // increase number of units found
    }
}
units = n;
// unit[] now contains the units found, units contains the number of them.

Where select_ variables contain the selection rectangle (x1, y1 set when starting to drag; x2, y2 updated every step while dragging) and obj_unit is the parent of object to select. Result is stored in unit array of the executing instance, and the number of results is stored in units variable.

Related posts:

5 thoughts on “GameMaker: ‘strategy’ unit selection

    • If you do not reset the counter/array when Shift is held, you would be adding units to an existing array.

      Switching to a ds_list might prove worthwhile for ease of removal.

      • thanks. also, how do i make it such that if i mouse select all of the units, only, lets say, three get highlighted?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.