private Time time;
@Override
public void update(float delta) {
for (EntityRef entity : entityManager.getEntitiesWith(SimpleAIComponent.class, CharacterMovementComponent.class, LocationComponent.class)) {
LocationComponent location = entity.getComponent(LocationComponent.class);
Vector3f worldPos = location.getWorldPosition();
// Skip this AI if not in a loaded chunk
if (!worldProvider.isBlockRelevant(worldPos)) {
continue;
}
SimpleAIComponent ai = entity.getComponent(SimpleAIComponent.class);
Vector3f drive = new Vector3f();
// TODO: shouldn't use local player, need some way to find nearest player
LocalPlayer localPlayer = CoreRegistry.get(LocalPlayer.class);
if (localPlayer != null) {
Vector3f dist = new Vector3f(worldPos);
dist.sub(localPlayer.getPosition());
double distanceToPlayer = dist.lengthSquared();
if (distanceToPlayer > 6 && distanceToPlayer < 16) {
// Head to player
ai.movementTarget.set(localPlayer.getPosition());
ai.followingPlayer = true;
entity.saveComponent(ai);
} else {
// Random walk
if (CoreRegistry.get(Time.class).getGameTimeInMs() - ai.lastChangeOfDirectionAt > 12000 || ai.followingPlayer) {
ai.movementTarget.set(worldPos.x + random.nextFloat(-500.0f, 500.0f), worldPos.y, worldPos.z + random.nextFloat(-500.0f, 500.0f));
ai.lastChangeOfDirectionAt = time.getGameTimeInMs();
ai.followingPlayer = false;
entity.saveComponent(ai);
}
}
Vector3f targetDirection = new Vector3f();
targetDirection.sub(ai.movementTarget, worldPos);
targetDirection.normalize();
drive.set(targetDirection);
float yaw = (float) Math.atan2(targetDirection.x, targetDirection.z);
AxisAngle4f axisAngle = new AxisAngle4f(0, 1, 0, yaw);
location.getLocalRotation().set(axisAngle);
entity.saveComponent(location);
}
entity.send(new CharacterMoveInputEvent(0, 0, 0, drive, false, false));
}
}