下面列出了怎么用org.bukkit.block.BlockFace的API类实例代码及写法,或者点击链接到github查看源代码。
private void rotateChest(Block chest, Integer direction) {
BlockFace blockFace;
switch (direction) {
case 0://East
blockFace = BlockFace.WEST;
break;
case 1://South
blockFace = BlockFace.NORTH;
break;
case 2://West
blockFace = BlockFace.EAST;
break;
case 3://North
blockFace = BlockFace.SOUTH;
break;
default:
blockFace = BlockFace.DOWN;
break;
}
BlockState state = chest.getState();
state.setData(new Chest(blockFace));
state.update();
}
@Override
public BlockFace getFacing() {
int data = getData() & 0x7;
switch (data) {
case 0x0:
return BlockFace.DOWN;
case 0x1:
return BlockFace.UP;
case 0x2:
return BlockFace.SOUTH;
case 0x3:
return BlockFace.NORTH;
case 0x4:
return BlockFace.EAST;
case 0x5:
return BlockFace.WEST;
default:
throw new IllegalArgumentException("Illegal facing direction " + data);
}
}
/**
* Add a sign to this region.
* @param location The location of the sign
* @param signType The type of the sign (WALL_SIGN or SIGN_POST)
* @param facing The orientation of the sign
* @param profile The profile to use with this sign (null for default)
*/
public void addSign(Location location, Material signType, BlockFace facing, String profile) {
int i = 0;
while(getRegion().getConfig().isSet("general.signs." + i)) {
i++;
}
String signPath = "general.signs." + i + ".";
getRegion().setSetting(signPath + "location", Utils.locationToConfig(location));
getRegion().setSetting(signPath + "facing", facing != null ? facing.name() : null);
getRegion().setSetting(signPath + "signType", signType != null ? signType.name() : null);
if(profile != null && !profile.isEmpty()) {
getRegion().setSetting(signPath + "profile", profile);
}
// Add to the map
RegionSign sign = new RegionSign(this, i + "");
signs.put(sign.getStringLocation(), sign);
allSigns.put(sign.getStringLocation(), sign);
signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
.add(sign);
}
@Override
public <T extends ControllableEntityHandle<? extends LivingEntity>> T createEntityHandle(ControllableEntity entity, Location location) {
SafeConstructor<ControllableEntityHandle> entityConstructor = getConstructorFor(entity.getEntityType());
EntityRegistrationEntry oldEntry = GameRegistry.get(IEntityRegistry.class).getDefaultEntryFor(entity.getEntityType());
GameRegistry.get(IEntityRegistry.class).register(new EntityRegistrationEntry(
entity.getEntityType().getName(),
entity.getEntityType().getId(),
entity.getEntityType().getHandleClass()
));
WorldServer worldServer = ((CraftWorld) location.getWorld()).getHandle();
T handle = (T) entityConstructor.getAccessor().invoke(worldServer, entity);
handle.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
worldServer.addEntity((net.minecraft.server.v1_8_R1.Entity) handle, CreatureSpawnEvent.SpawnReason.CUSTOM);
GameRegistry.get(IEntityRegistry.class).register(oldEntry);
Material beneath = location.getBlock().getRelative(BlockFace.DOWN).getType();
if (beneath.isBlock()) { // What lies beneath
((Entity) handle).onGround = true;
}
return handle;
}
@EventHandler (priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e){
Block block = e.getBlock();
// For tall flowers start with the bottom block.
Block below = block.getRelative(BlockFace.DOWN);
if (isFlower(below)){
block = below;
}
if (isFlower(block)){
Location blockLoc = block.getLocation().add(.5,.5,.5);
block.setType(Material.AIR);
UhcItems.spawnExtraXp(blockLoc, expPerFlower);
int random = RandomUtils.randomInteger(0, flowerDrops.size()-1);
ItemStack drop = flowerDrops.get(random);
blockLoc.getWorld().dropItem(blockLoc, drop);
}
}
@Override
public ControllablePlayerHandle createPlayerHandle(ControllablePlayer player, Location location, String name, UUID uuid) {
WorldServer worldServer = ((CraftWorld) location.getWorld()).getHandle();
if (name.length() > 16)
name = name.substring(0, 16);
GameProfile profile = new GameProfile(uuid.toString().replaceAll("-", ""), name);
ControllablePlayerEntity handle = new ControllablePlayerEntity(worldServer.getMinecraftServer(), worldServer, profile, new PlayerInteractManager(worldServer), player);
handle.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
worldServer.addEntity(handle);
handle.world.players.remove(handle);
if (location.getBlock().getRelative(BlockFace.DOWN).getType().isBlock())
handle.onGround = true;
return handle;
}
@Override
public void onInteract(Player p, Block b) {
Block dispenser = b.getRelative(BlockFace.DOWN);
Dispenser disp = (Dispenser) dispenser.getState();
Inventory inv = disp.getInventory();
List<ItemStack[]> inputs = RecipeType.getRecipeInputList(this);
for (int i = 0; i < inputs.size(); i++) {
if (isCraftable(inv, inputs.get(i))) {
ItemStack output = RecipeType.getRecipeOutputList(this, inputs.get(i)).clone();
if (Slimefun.hasUnlocked(p, output, true)) {
craft(inv, dispenser, p, b, output);
}
return;
}
}
SlimefunPlugin.getLocalization().sendMessage(p, "machines.pattern-not-found", true);
}
@Override
public boolean setSignFacing(Block block, BlockFace facing) {
if (block == null || facing == null) {
return false;
}
BlockState blockState = block.getState();
if (blockState == null) {
return false;
}
BlockData blockData = blockState.getBlockData();
if (blockData == null) {
return false;
}
if(blockData instanceof WallSign) {
((WallSign) blockData).setFacing(facing);
} else if(blockData instanceof Sign) {
((Sign) blockData).setRotation(facing);
} else {
return false;
}
block.setBlockData(blockData);
return true;
}
private static PlayerEvent getPlayerBucketEvent(boolean isFilling, EntityPlayer who, int clickedX, int clickedY, int clickedZ, EnumFacing clickedFace, ItemStack itemstack, net.minecraft.item.Item item) {
Player player = (who == null) ? null : (Player) who.getBukkitEntity();
CraftItemStack itemInHand = CraftItemStack.asNewCraftStack(item);
Material bucket = CraftMagicNumbers.getMaterial(itemstack.getItem());
CraftWorld craftWorld = (CraftWorld) player.getWorld();
CraftServer craftServer = (CraftServer) player.getServer();
Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ);
BlockFace blockFace = CraftBlock.notchToBlockFace(clickedFace);
PlayerEvent event = null;
if (isFilling) {
event = new PlayerBucketFillEvent(player, blockClicked, blockFace, bucket, itemInHand);
((PlayerBucketFillEvent) event).setCancelled(!canBuild(craftWorld, player, clickedX, clickedZ));
} else {
event = new PlayerBucketEmptyEvent(player, blockClicked, blockFace, bucket, itemInHand);
((PlayerBucketEmptyEvent) event).setCancelled(!canBuild(craftWorld, player, clickedX, clickedZ));
}
craftServer.getPluginManager().callEvent(event);
return event;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockChange(BlockTransformEvent event) {
BlockState newState = event.getNewState();
Block block = newState.getBlock();
long pos = encodePos(block);
// Only breaks are credited. Making a bridge fall by updating a block
// does not credit you with breaking the bridge.
ParticipantState breaker =
event.isBreak() ? ParticipantBlockTransformEvent.getPlayerState(event) : null;
if (!(event.getCause() instanceof BlockFallEvent)) {
this.disturb(pos, newState, breaker);
}
for (BlockFace face : NEIGHBORS) {
this.disturb(neighborPos(pos, face), block.getRelative(face).getState(), breaker);
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void repairChunk(ChunkLoadEvent event) {
if (this.repairedChunks.put(event.getWorld(), event.getChunk())) {
// Replace formerly invisible half-iron-door blocks with barriers
for (Block ironDoor : event.getChunk().getBlocks(Material.IRON_DOOR_BLOCK)) {
BlockFace half = (ironDoor.getData() & 8) == 0 ? BlockFace.DOWN : BlockFace.UP;
if (ironDoor.getRelative(half.getOppositeFace()).getType() != Material.IRON_DOOR_BLOCK) {
ironDoor.setType(Material.BARRIER, false);
}
}
// Remove all block 36 and remember the ones at y=0 so VoidFilter can check them
for (Block block36 : event.getChunk().getBlocks(Material.PISTON_MOVING_PIECE)) {
if (block36.getY() == 0) {
block36Locations
.get(event.getWorld())
.add(block36.getX(), block36.getY(), block36.getZ());
}
block36.setType(Material.AIR, false);
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void block(BlockFromToEvent event) {
if (!useEnhanceProtection) {
return;
}
if (DisplayItem.getNowUsing() != DisplayType.REALITEM) {
return;
}
final Block targetBlock = event.getToBlock();
final Block shopBlock = targetBlock.getRelative(BlockFace.DOWN);
final Shop shop = getShopNature(shopBlock.getLocation(),true);
if (shop == null) {
return;
}
event.setCancelled(true);
if (shop.getDisplay() != null) {
shop.getDisplay().remove();
}
sendAlert(
"[DisplayGuard] Liuqid "
+ targetBlock.getLocation()
+ " trying flow to top of shop, QuickShop already cancel it.");
}
public Uncarried(Flag flag, Post post, @Nullable Location location) {
super(flag, post);
if(location == null) location = flag.getReturnPoint(post);
this.location = new Location(location.getWorld(),
location.getBlockX() + 0.5,
location.getBlockY(),
location.getBlockZ() + 0.5,
location.getYaw(),
location.getPitch());
if(!flag.getMatch().getWorld().equals(this.location.getWorld())) {
throw new IllegalStateException("Tried to place flag in the wrong world");
}
Block block = this.location.getBlock();
if(block.getType() == Material.STANDING_BANNER) {
// Banner may already be here at match start
this.oldBlock = BlockStateUtils.cloneWithMaterial(block, Material.AIR);
} else {
this.oldBlock = block.getState();
}
this.oldBase = block.getRelative(BlockFace.DOWN).getState();
}
public List<PlayerShopkeeper> getShopkeeperOwnersOfChest(String worldName, int x, int y, int z) {
List<PlayerShopkeeper> result = new ArrayList<PlayerShopkeeper>();
// checking this exact block:
List<PlayerShopkeeper> shopkeepers = this.getShopkeepers(worldName, x, y, z);
if (shopkeepers != null) {
result.addAll(shopkeepers);
}
// including the directly adjacent blocks as well:
for (BlockFace face : CHEST_PROTECTED_FACES) {
shopkeepers = this.getShopkeepers(worldName, x + face.getModX(), y + face.getModY(), z + face.getModZ());
if (shopkeepers != null) {
result.addAll(shopkeepers);
}
}
return result;
}
/**
* Find a block that is adjacent to another block on any of the block's 6 sides
* given a Material
*
* @param block
* @param material
* @param ignore
* @return
*/
public Block findAdjacentBlockOnAllSides(Block block, Material material, Block... ignore) {
BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST,
BlockFace.UP, BlockFace.DOWN};
List<Block> ignoreList = Arrays.asList(ignore);
for (BlockFace face : faces) {
Block adjacentBlock = block.getRelative(face);
if (adjacentBlock.getType() == material && !ignoreList.contains(adjacentBlock)) {
return adjacentBlock;
}
}
return null;
}
private void stomp(EntityDamageEvent e) {
Player p = (Player) e.getEntity();
p.getWorld().playSound(p.getLocation(), Sound.ENTITY_ZOMBIE_BREAK_WOODEN_DOOR, 1F, 2F);
p.setVelocity(new Vector(0.0, 0.7, 0.0));
for (Entity n : p.getNearbyEntities(4, 4, 4)) {
if (n instanceof LivingEntity && !n.getUniqueId().equals(p.getUniqueId())) {
Vector velocity = n.getLocation().toVector().subtract(p.getLocation().toVector()).normalize().multiply(1.4);
n.setVelocity(velocity);
if (!(n instanceof Player) || (p.getWorld().getPVP() && SlimefunPlugin.getProtectionManager().hasPermission(p, n.getLocation(), ProtectableAction.PVP))) {
EntityDamageByEntityEvent event = new EntityDamageByEntityEvent(p, n, DamageCause.ENTITY_ATTACK, e.getDamage() / 2);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) ((LivingEntity) n).damage(e.getDamage() / 2);
}
}
}
for (BlockFace face : BlockFace.values()) {
Block b = p.getLocation().getBlock().getRelative(BlockFace.DOWN).getRelative(face);
p.getWorld().playEffect(b.getLocation(), Effect.STEP_SOUND, b.getType());
}
}
@Override
protected void fish(Block b, BlockMenu menu) {
Block water = b.getRelative(BlockFace.DOWN);
if (water.getType() == Material.WATER) {
water.getWorld().playSound(water.getLocation(), Sound.ENTITY_PLAYER_SPLASH, 0.3F, 0.7F);
if (ThreadLocalRandom.current().nextInt(100) < 10 * getTier()) {
ItemStack drop = fishingLoot.getRandom();
if (menu.fits(drop, getOutputSlots())) {
menu.pushItem(drop, getOutputSlots());
}
}
}
}
/**
* Get the direction that this door is facing.
* <p>
* Undefined if <code>isTopHalf()</code> is true.
*
* @return the direction
*/
public BlockFace getFacing() {
byte data = (byte) (getData() & 0x3);
switch (data) {
case 0:
return BlockFace.WEST;
case 1:
return BlockFace.NORTH;
case 2:
return BlockFace.EAST;
case 3:
return BlockFace.SOUTH;
default:
throw new IllegalStateException("Unknown door facing (data: " + data + ")");
}
}
public TableSaw(Category category, SlimefunItemStack item) {
super(category, item, new ItemStack[] { null, null, null, new ItemStack(Material.SMOOTH_STONE_SLAB), new ItemStack(Material.STONECUTTER), new ItemStack(Material.SMOOTH_STONE_SLAB), null, new ItemStack(Material.IRON_BLOCK), null }, new ItemStack[0], BlockFace.SELF);
for (Material log : Tag.LOGS.getValues()) {
Optional<Material> planks = MaterialConverter.getPlanksFromLog(log);
if (planks.isPresent()) {
displayedRecipes.add(new ItemStack(log));
displayedRecipes.add(new ItemStack(planks.get(), 8));
}
}
}
public static Block getBedNeighbor(Block head) {
if (isBedBlock(head.getRelative(BlockFace.EAST))) {
return head.getRelative(BlockFace.EAST);
} else if (isBedBlock(head.getRelative(BlockFace.WEST))) {
return head.getRelative(BlockFace.WEST);
} else if (isBedBlock(head.getRelative(BlockFace.SOUTH))) {
return head.getRelative(BlockFace.SOUTH);
} else {
return head.getRelative(BlockFace.NORTH);
}
}
@EventHandler
public void onTNTSheepUsed(PlayerInteractEvent event) {
Player player = event.getPlayer();
if (!Main.isPlayerInGame(player)) {
return;
}
GamePlayer gamePlayer = Main.getPlayerGameProfile(player);
Game game = gamePlayer.getGame();
if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (game.getStatus() == GameStatus.RUNNING && !gamePlayer.isSpectator && event.getItem() != null) {
ItemStack stack = event.getItem();
String unhidden = APIUtils.unhashFromInvisibleStringStartsWith(stack, TNT_SHEEP_PREFIX);
if (unhidden != null) {
event.setCancelled(true);
double speed = Double.parseDouble(unhidden.split(":")[2]);
double follow = Double.parseDouble(unhidden.split(":")[3]);
double maxTargetDistance = Double.parseDouble(unhidden.split(":")[4]);
int explosionTime = Integer.parseInt(unhidden.split(":")[5]);
Location startLocation;
if (event.getClickedBlock() == null) {
startLocation = player.getLocation();
} else {
startLocation = event.getClickedBlock().getRelative(BlockFace.UP).getLocation();
}
TNTSheep sheep = new TNTSheep(game, player, game.getTeamOfPlayer(player),
startLocation, stack, speed, follow, maxTargetDistance, explosionTime);
sheep.spawn();
}
}
}
}
private void onBlockBreak(Block block){
for (BlockFace face : NEIGHBOURS) {
final Block relative = block.getRelative(face);
if (!UniversalMaterial.isLeaves(relative.getType())){
continue; // Not a leave so don't fast decay
}
if (findLog(relative, DECAY_RANGE)){
continue; // A log is too close so don't fast decay
}
Bukkit.getScheduler().runTaskLater(UhcCore.getPlugin(), new Runnable() {
@Override
public void run() {
if (!UniversalMaterial.isLeaves(relative.getType())){
return; // Double check to make sure the block hasn't changed since
}
LeavesDecayEvent event = new LeavesDecayEvent(relative);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
relative.breakNaturally();
relative.getWorld().playSound(relative.getLocation(), UniversalSound.BLOCK_GRASS_BREAK.getSound(), 1, 1);
}
}
}, 5);
}
}
Interaction(Player p, EquipmentSlot hand, ItemStack item, Block clickedBlock, BlockFace blockFace, Action action) {
this.p = p;
this.hand = hand;
this.item = item;
this.clickedBlock = clickedBlock;
this.blockFace = blockFace;
this.action = action;
}
@EventHandler(priority = EventPriority.HIGH)
public void onMultiBlockPlace(BlockMultiPlaceEvent e) {
for (BlockState blockState : e.getReplacedBlockStates()) {
Block below = blockState.getBlock().getRelative(BlockFace.DOWN);
if (shopUtils.isShop(below.getLocation())) {
Shop shop = shopUtils.getShop(below.getLocation());
if (shop.getItem() != null) {
shop.getItem().resetForPlayer(e.getPlayer());
}
e.setCancelled(true);
}
}
}
public static FacingObject loadFromConfig(ConfigurationSection configSection)
{
if(configSection != null)
{
//Location loc = ConfigManager.getLocation(configSection.getConfigurationSection("Location"));
Loc loc = new Loc(configSection.getConfigurationSection("Location"));
BlockFace facing = BlockFace.valueOf(configSection.getString("FacingDirection"));
return new FacingObject(facing,loc);
}
return null;
}
/**
* Converts block face direction to radial degrees. Returns 0 if block face
* is not radial.
*
* @param face
* @return degrees
*/
public static float blockFaceToFloat(BlockFace face) {
switch (face) {
case EAST:
return 90F;
case EAST_NORTH_EAST:
return 67.5F;
case EAST_SOUTH_EAST:
return 0F;
case NORTH:
return 0F;
case NORTH_EAST:
return 45F;
case NORTH_NORTH_EAST:
return 22.5F;
case NORTH_NORTH_WEST:
return 337.5F;
case NORTH_WEST:
return 315F;
case SOUTH:
return 180F;
case SOUTH_EAST:
return 135F;
case SOUTH_SOUTH_EAST:
return 157.5F;
case SOUTH_SOUTH_WEST:
return 202.5F;
case SOUTH_WEST:
return 225F;
case WEST:
return 270F;
case WEST_NORTH_WEST:
return 292.5F;
case WEST_SOUTH_WEST:
return 247.5F;
default:
return 0F;
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
PlayerInventory inv = player.getInventory();
ItemStack item = inv.getItemInMainHand();
if (event.getHand() != null)
switch (event.getHand()) {
case OFF_HAND:
item = inv.getItemInOffHand();
break;
default:
break;
}
if (AdditionsAPI.isCustomItem(item)) {
CustomItemPlayerInteractEvent customEvent = new CustomItemPlayerInteractEvent(event,
new CustomItemStack(item));
Bukkit.getServer().getPluginManager().callEvent(customEvent);
}
if (event.getAction() != null && event.getAction() == Action.RIGHT_CLICK_BLOCK
&& ToolType.getToolType(item.getType()) != null
&& ToolType.getToolType(item.getType()).equals(ToolType.HOE)) {
Block block = event.getClickedBlock();
Material material = block.getType();
Location blockLoc = block.getLocation();
blockLoc.setY(blockLoc.getBlockY() + 1);
Material materialUp = blockLoc.getBlock().getType();
@SuppressWarnings("deprecation")
byte data = block.getData();
BlockFace face = event.getBlockFace();
if (materialUp == Material.AIR && (face == BlockFace.UP || face == BlockFace.EAST || face == BlockFace.NORTH
|| face == BlockFace.SOUTH || face == BlockFace.WEST))
if (shouldPlaySound(material, item, data, player))
player.playSound(block.getLocation(), "additionsapi.hoe.till", 1.0F, 1.0F);
}
}
static BlockState getRelative(BlockState block, BlockFace face) {
return block
.getWorld()
.getBlockAt(
block.getX() + face.getModX(),
block.getY() + face.getModY(),
block.getZ() + face.getModZ())
.getState();
}
private Block[] findPistons(Block chest) {
Block northern = chest.getRelative(BlockFace.NORTH);
if (northern.getType() == Material.PISTON) {
return new Block[] { northern, chest.getRelative(BlockFace.SOUTH) };
}
else {
return new Block[] { chest.getRelative(BlockFace.WEST), chest.getRelative(BlockFace.EAST) };
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onEntityChangeBlockEvent(EntityChangeBlockEvent e) {
EntityType type = e.getEntityType();
if (type != EntityType.FALLING_BLOCK) {
return;
}
Entity entity = e.getEntity();
if (!fallingAnvils.contains(entity)) {
return;
}
Block block = e.getBlock();
Block under = block.getRelative(BlockFace.DOWN);
fallingAnvils.remove(entity);
e.setCancelled(true);
if (!game.canSpleef(under)) {
entity.remove();
return;
}
Material material = under.getType();
under.setType(Material.AIR);
World world = under.getWorld();
Sound anvilLandSound = Game.getSoundEnumType("ANVIL_LAND");
if (anvilLandSound != null) {
world.playSound(block.getLocation(), anvilLandSound, 1.0f, 1.0f);
}
if (game.getPropertyValue(GameProperty.PLAY_BLOCK_BREAK)) {
world.playEffect(under.getLocation(), Effect.STEP_SOUND, material.getId());
}
}