Citizens2/main/src/main/java/net/citizensnpcs/nms/v1_10_R1/entity/MobEntityController.java

61 lines
2.1 KiB
Java
Raw Normal View History

package net.citizensnpcs.nms.v1_10_R1.entity;
import java.lang.reflect.Constructor;
import java.util.Map;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
2016-06-09 12:25:27 +02:00
import org.bukkit.craftbukkit.v1_10_R1.CraftWorld;
import org.bukkit.entity.Entity;
2012-08-03 15:18:10 +02:00
import com.google.common.collect.Maps;
2016-03-01 04:12:13 +01:00
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.npc.AbstractEntityController;
2016-06-09 12:25:27 +02:00
import net.minecraft.server.v1_10_R1.World;
2016-03-01 04:12:13 +01:00
public abstract class MobEntityController extends AbstractEntityController {
2012-12-07 16:04:31 +01:00
private final Constructor<?> constructor;
2012-09-16 06:29:08 +02:00
protected MobEntityController(Class<?> clazz) {
2013-12-24 11:55:01 +01:00
super(clazz);
2012-08-03 15:18:10 +02:00
this.constructor = getConstructor(clazz);
}
@Override
protected Entity createEntity(Location at, NPC npc) {
2016-06-09 12:25:27 +02:00
net.minecraft.server.v1_10_R1.Entity entity = createEntityFromClass(((CraftWorld) at.getWorld()).getHandle(),
npc);
entity.setPositionRotation(at.getX(), at.getY(), at.getZ(), at.getYaw(), at.getPitch());
// entity.onGround isn't updated right away - we approximate here so
// that things like pathfinding still work *immediately* after spawn.
org.bukkit.Material beneath = at.getBlock().getRelative(BlockFace.DOWN).getType();
if (beneath.isBlock()) {
2012-12-07 16:04:31 +01:00
entity.onGround = true;
}
return entity.getBukkitEntity();
}
2016-06-09 12:25:27 +02:00
private net.minecraft.server.v1_10_R1.Entity createEntityFromClass(Object... args) {
try {
2016-06-09 12:25:27 +02:00
return (net.minecraft.server.v1_10_R1.Entity) constructor.newInstance(args);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
2012-12-07 16:04:31 +01:00
private static Constructor<?> getConstructor(Class<?> clazz) {
Constructor<?> constructor = CONSTRUCTOR_CACHE.get(clazz);
2012-08-03 15:18:10 +02:00
if (constructor != null)
return constructor;
try {
2012-08-03 15:18:10 +02:00
return clazz.getConstructor(World.class, NPC.class);
} catch (Exception ex) {
2012-08-03 15:18:10 +02:00
throw new IllegalStateException("unable to find an entity constructor");
}
}
2013-07-09 18:14:28 +02:00
private static final Map<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE = Maps.newHashMap();
2012-02-04 09:13:20 +01:00
}