Here is an generic entity which follows a set of waypoints:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import pojahn.game.core.Collisions;
import pojahn.game.core.MobileEntity;
import pojahn.game.events.Event;
import com.badlogic.gdx.math.Vector2;
public class PathDrone extends MobileEntity {
public static class Waypoint {
public final float targetX, targetY;
public final int frames;
public final boolean jump;
public final Event event;
public Waypoint(float targetX, float targetY, int frames, boolean jump, Event event) {
this.targetX = targetX;
this.targetY = targetY;
this.frames = frames;
this.jump = jump;
this.event = event;
}
public Waypoint(float targetX, float targetY) {
this(targetX, targetY, 0, false, null);
}
}
private List < Waypoint > waypoints;
private int dataCounter, stillCounter;
private boolean playEvent;
public PathDrone(float x, float y) {
move(x, y);
waypoints = new ArrayList < > ();
dataCounter = stillCounter = 0;
}
public void appendPath(float x, float y, int frames, boolean jump, Event event) {
waypoints.add(new Waypoint(x, y, frames, jump, event));
}
public void appendPath(Vector2 loc, int frames, boolean jump, Event event) {
waypoints.add(new Waypoint(loc.x, loc.y, frames, jump, event));
}
public void appendPath(Waypoint pd) {
waypoints.add(pd);
}
public void appendPath(Waypoint[] list) {
waypoints.addAll(Arrays.asList(list));
}
public void appendPath(float x, float y) {
appendPath(x, y, 0, false, null);
}
public void appendPath() {
waypoints.add(new Waypoint(x(), y(), 0, false, null));
}
public void appendReversed() {
List < Waypoint > reversed = new ArrayList < > (waypoints);
reversed.remove(reversed.size() - 1);
Collections.reverse(reversed);
waypoints.addAll(reversed);
}
public void clearData() {
waypoints.clear();
rollback();
}
public void rollback() {
dataCounter = stillCounter = 0;
}
@Override
public void logistics() {
if (!waypoints.isEmpty() && getMoveSpeed() > 0) {
if (dataCounter >= waypoints.size())
dataCounter = 0;
Waypoint wp = waypoints.get(dataCounter);
if (reached(wp)) {
if (++stillCounter > wp.frames)
dataCounter++;
x = wp.targetX;
y = wp.targetY;
if (playEvent && wp.event != null) {
wp.event.eventHandling();
playEvent = false;
}
} else {
playEvent = true;
stillCounter = 0;
if (wp.jump) {
x = wp.targetX;
y = wp.targetY;
} else
moveTowards(wp.targetX, wp.targetY);
}
}
}
protected boolean reached(Waypoint pd) {
return getMoveSpeed() > Collisions.distance(pd.targetX, pd.targetY, x(), y());
}
protected void moveTowards(float targetX, float targetY) {
float fX = targetX - x();
float fY = targetY - y();
float dist = (float) Math.sqrt(fX * fX + fY * fY);
float step = movespeed / dist;
x += fX * step;
y += fY * step);
}
}
You can use it like this:
PathDrone pd = new PathDrone();
pd.appendPath(10, 4);
pd.appendPath(10, 0);
pd.appendPath(9, 0);
pd.appendPath(0, 0);
logictics should you call every frame in your game loop.