Within my game there are many entities, where each entity has a path (Array<Vector2>
) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null
). updateMoveAttributes
is called every frame for every entity, so it is important that it is efficient.
Note that my entity's direction is in radians, ranging from - Math.PI
to Math.PI
, since this is what Math.atan2
returns.
The below snippet contains updateMoveAttributes
and its supporting methods.
private final Array<Vector2> path = new Array<>(); private int pathIndex = 0; private static final float EPSILON = 1e-3f; private float getXDifference(Vector2 pathComponent) { float xDifference = pathComponent.x - getSprite().getX(); xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference; return xDifference; } private float getYDifference(Vector2 pathComponent) { float yDifference = pathComponent.y - getSprite().getY(); yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference; return yDifference; } public float orient(Vector2 pathComponent) { float xDiff = getXDifference(pathComponent); float yDiff = getYDifference(pathComponent); return (float) Math.atan2(yDiff, xDiff); } void updateMoveAttributes() { // No path assigned if (getPath().size == 0) return; // No more path to travel if (getPathIndex() == getPath().size) { setSpeed(0); return; } Vector2 nextPathComponent = getPath().get(getPathIndex()); float angleToComponent = orient(nextPathComponent); setDirection(angleToComponent); float xDiff = getXDifference(nextPathComponent); float yDiff = getYDifference(nextPathComponent); boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2); boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0); boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI); boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0); // Indicates that we have passed the path component we are on route to, adjust course with respect // to next available path component. if (pastY && pastX) setPathIndex(getPathIndex() + 1); // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed setSpeed(getMovementSpeed()); } public Array<Vector2> getPath() { return path; }