Last Updated: January 28, 2019
· drabiter

Grab a unit from a given coordinate

It means that you need to handle an unit/entity that selected by player with mouse click. To do this (dirty) trick make sure your unit class has identifier field like String or integer or else. Assume that we already have the click's coordinate (x, y) and String as unit's identity. As unit may be part of Stage, you can put them into one Group (say, unitGroup).

First, create a "collection" to "remember" all units' positions. The position data could be Vector2.

HashMap<String, Vector2> units;

Then you can pool an unit that clicked on (x, y).

public Unit findByLocation(float x, float y) {
    Unit unit = null;
    for (Entry<String, Vector2> maps : units.entrySet()) {
        Vector2 v = maps.getValue();
        if (x > v.x && y > v.y && x < v.x + SPRITE_.SIZE && y < v.y + SPRITE_.SIZE) {
            unit = (Unit) unitGroup.findActor(maps.getKey());
            return unit;
    return unit;

The main down side of this method is that we need to update unit's position in the collection when changed.

public void updateUnitPosition(Unit unit) {
    Vector2 v = units.get(;
    v.x = unit.x;
    v.y = unit.y;