net.minecraftforge.fml.common.eventhandler.EventPriority Java Examples

The following examples show how to use net.minecraftforge.fml.common.eventhandler.EventPriority. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PotionTimeSlow.java    From Wizardry with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onTick(LivingEvent.LivingUpdateEvent event) {
	EntityLivingBase e = event.getEntityLiving();
	if(e.isPotionActive(ModPotions.TIME_SLOW) && timeScale(e) == 0) {
		boolean shouldFreeze = true;
		if(e.isDead || e.getHealth() <= 0) {
			shouldFreeze = false;
		}
		if(e instanceof EntityDragon && ((EntityDragon) e).getPhaseManager().getCurrentPhase().getType() == PhaseList.DYING) {
			shouldFreeze = false;
		}
		if(shouldFreeze) {
			handleImportantEntityTicks(e);
			event.setCanceled(true);
		}
	}
}
 
Example #2
Source File: ContainerEventHandler.java    From NotEnoughItems with MIT License 6 votes vote down vote up
@SubscribeEvent (priority = EventPriority.LOWEST, receiveCanceled = true)//We need to be called before JEI.
public void onGuiMouseEventpre(MouseInputEvent.Pre event) {
    if (Mouse.getEventButton() == -1 || event.getGui() == null || !Mouse.getEventButtonState()) {
        return;
    }
    Point mouse = GuiDraw.getMousePosition();
    int eventButton = Mouse.getEventButton();
    if (JEIIntegrationManager.searchBoxOwner == EnumItemBrowser.JEI) {
        GuiTextFieldFilter fieldFilter = JEIIntegrationManager.getTextFieldFilter();
        if (fieldFilter != null && fieldFilter.isMouseOver(mouse.x, mouse.y)) {
            if (eventButton == 0) {
                if (fieldFilter.isFocused() && (System.currentTimeMillis() - lastSearchBoxClickTime < 500)) {//double click
                    NEIClientConfig.world.nbt.setBoolean("searchinventories", !SearchField.searchInventories());
                    NEIClientConfig.world.saveNBT();
                    lastSearchBoxClickTime = 0L;
                } else {
                    lastSearchBoxClickTime = System.currentTimeMillis();
                }
            } else if (eventButton == 1) {
                NEIClientConfig.setSearchExpression("", false);
                LayoutManager.searchField.setText("", false);
            }
        }
    }
}
 
Example #3
Source File: HandlerHammer.java    From ExNihiloAdscensio with MIT License 6 votes vote down vote up
@SubscribeEvent(priority=EventPriority.LOWEST)
public void hammer(BlockEvent.HarvestDropsEvent event)
{
	if (event.getWorld().isRemote || event.getHarvester() == null || event.isSilkTouching())
		return;

	ItemStack held = event.getHarvester().getHeldItemMainhand();
	
	if (!isHammer(held))
		return;
	
	List<ItemStack> rewards = HammerRegistry.getRewardDrops(event.getWorld().rand, event.getState(), ((IHammer) held.getItem()).getMiningLevel(held), event.getFortuneLevel());
	
	if (rewards != null && rewards.size() > 0)
	{
		event.getDrops().clear();
		event.setDropChance(1.0F);
		event.getDrops().addAll(rewards);
	}
}
 
Example #4
Source File: SingleFluidBucketFillHandler.java    From OpenModsLib with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGH)
public void onBucketFill(FillBucketEvent evt) {
	if (evt.getResult() != Result.DEFAULT) return;

	if (evt.getEmptyBucket().getItem() != EMPTY_BUCKET) return;

	final RayTraceResult target = evt.getTarget();
	if (target == null || target.typeOfHit != RayTraceResult.Type.BLOCK) return;

	final TileEntity te = evt.getWorld().getTileEntity(target.getBlockPos());
	if (te == null) return;

	if (te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit)) {
		final IFluidHandler source = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, target.sideHit);

		final FluidStack drained = source.drain(containedFluid, false);
		if (containedFluid.isFluidStackIdentical(drained)) {
			source.drain(containedFluid, true);
			evt.setFilledBucket(filledBucket.copy());
			evt.setResult(Result.ALLOW);
		}
	}
}
 
Example #5
Source File: CMMEventHandler.java    From Custom-Main-Menu with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST)
public void openGui(GuiOpenEvent event)
{
	if (event.getGui() instanceof GuiMainMenu)
	{
		GuiCustom customMainMenu = CustomMainMenu.INSTANCE.config.getGUI("mainmenu");
		if (customMainMenu != null)
		{
			event.setGui(customMainMenu);
		}
	}
	else if (event.getGui() instanceof GuiCustom)
	{
		GuiCustom custom = (GuiCustom) event.getGui();

		GuiCustom target = CustomMainMenu.INSTANCE.config.getGUI(custom.guiConfig.name);
		if (target != custom)
		{
			event.setGui(target);
		}
	}
}
 
Example #6
Source File: PayloadSpoofer.java    From ForgeHax with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onIncomingPacket(PacketEvent.Incoming.Pre event) {
  String channel;
  ByteBuf packetBuffer;
  final Packet packet = event.getPacket();

  if (packet instanceof SPacketCustomPayload || packet instanceof FMLProxyPacket) {
    if (packet instanceof SPacketCustomPayload) {
      channel = ((SPacketCustomPayload) packet).getChannelName();
      packetBuffer = ((SPacketCustomPayload) packet).getBufferData();
    } else {
      channel = ((FMLProxyPacket) packet).channel();
      packetBuffer = ((FMLProxyPacket) packet).payload();
    }
    
    if (isBlockedPacket(channel, packetBuffer)) {
      event.setCanceled(true);
    }
  }
}
 
Example #7
Source File: PayloadSpoofer.java    From ForgeHax with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onOutgoingPacket(PacketEvent.Outgoing.Pre event) {
  String channel;
  ByteBuf packetBuffer;
  final Packet packet = event.getPacket();
  
  if (packet instanceof CPacketCustomPayload || packet instanceof FMLProxyPacket) {
    if (packet instanceof CPacketCustomPayload) {
      channel = ((CPacketCustomPayload) packet).getChannelName();
      packetBuffer = ((CPacketCustomPayload) packet).getBufferData();
    } else {
      channel = ((FMLProxyPacket) packet).channel();
      packetBuffer = ((FMLProxyPacket) packet).payload();
    }
    
    if (isBlockedPacket(channel, packetBuffer)) {
      event.setCanceled(true);
    }
  }
}
 
Example #8
Source File: PositionRotationManager.java    From ForgeHax with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPacketReceived(PacketEvent.Incoming.Pre event) {
  if (!enabled.get()) return;

  if(event.getPacket() instanceof SPacketPlayerPosLook) {
    // when the server sets the rotation we use that instead
    final SPacketPlayerPosLook packet = event.getPacket();
    
    float pitch = packet.getPitch();
    float yaw = packet.getYaw();
    
    Angle va = gState.getClientAngles();
    
    if(packet.getFlags().contains(EnumFlags.X_ROT))
      pitch += va.getPitch();
    
    if(packet.getFlags().contains(EnumFlags.Y_ROT))
      yaw += va.getYaw();
    
    gState.setServerAngles(pitch, yaw);
    gState.setInitialized(true);
  }
}
 
Example #9
Source File: GuiEnderUtilities.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOW)
public static void onMouseInputEventPre(MouseInputEvent.Pre event)
{
    // Handle the mouse input inside all of the mod's GUIs via the event and then cancel the event,
    // so that some mods like Inventory Sorter don't try to sort the Ender Utilities inventories.
    // Using priority LOW should still allow even older versions of Item Scroller to work,
    // since it uses normal priority.
    if (event.getGui() instanceof GuiEnderUtilities)
    {
        try
        {
            event.getGui().handleMouseInput();
            event.setCanceled(true);
        }
        catch (IOException e)
        {
            EnderUtilities.logger.warn("Exception while executing handleMouseInput() on {}", event.getGui().getClass().getName());
        }
    }
}
 
Example #10
Source File: EventTooltip.java    From Levels with GNU General Public License v2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onTooltip(ItemTooltipEvent event)
{
	ArrayList<String> tooltip = (ArrayList<String>) event.getToolTip();
	ItemStack stack = event.getItemStack();
	NBTTagCompound nbt = NBTHelper.loadStackNBT(stack);
	
	if (stack != null && nbt != null)
	{
		if (stack.getItem() instanceof ItemSword || stack.getItem() instanceof ItemArmor || stack.getItem() instanceof ItemBow || stack.getItem() instanceof ItemShield || stack.getItem() instanceof ItemTool)
		{
			Rarity rarity = Rarity.getRarity(nbt);
			
			if (rarity != Rarity.DEFAULT)
			{
				addTooltips(tooltip, stack, nbt);
			}
		}
	}
}
 
Example #11
Source File: EventsCommon.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onEntityJoinWorldEvent(EntityJoinWorldEvent event) {
    Entity entity = event.getEntity();

    World world = entity.world;
    BlockPos posAt = new BlockPos(entity);

    Optional<PhysicsObject> physicsObject = ValkyrienUtils.getPhysicsObject(world, posAt);
    if (!event.getWorld().isRemote && physicsObject.isPresent()
        && !(entity instanceof EntityFallingBlock)) {
        if (entity instanceof EntityArmorStand
            || entity instanceof EntityPig || entity instanceof EntityBoat) {
            EntityMountable entityMountable = new EntityMountable(world,
                entity.getPositionVector(), CoordinateSpaceType.SUBSPACE_COORDINATES, posAt);
            world.spawnEntity(entityMountable);
            entity.startRiding(entityMountable);
        }
        physicsObject.get()
            .getShipTransformationManager()
            .getCurrentTickTransform().transform(entity,
            TransformType.SUBSPACE_TO_GLOBAL);
        // TODO: This should work but it doesn't because of sponge. Instead we have to rely on MixinChunk.preAddEntity() to fix this
        // event.setCanceled(true);
        // event.getWorld().spawnEntity(entity);
    }
}
 
Example #12
Source File: LogoutSpot.java    From ForgeHax with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOW)
public void onRenderGameOverlayEvent(Render2DEvent event) {
  if (!render.get()) {
    return;
  }
  
  synchronized (spots) {
    spots.forEach(
        spot -> {
          Vec3d top = spot.getTopVec();
          Plane upper = VectorUtils.toScreen(top);
          if (upper.isVisible()) {
            double distance = getLocalPlayer().getPositionVector().distanceTo(top);
            String name = String.format("%s (%.1f)", spot.getName(), distance);
            SurfaceHelper.drawTextShadow(
                name,
                (int) upper.getX() - (SurfaceHelper.getTextWidth(name) / 2),
                (int) upper.getY() - (SurfaceHelper.getTextHeight() + 1),
                Colors.RED.toBuffer());
          }
        });
  }
}
 
Example #13
Source File: ItemHeartUpgrade.java    From Cyberware with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST)
public void handleHurt(LivingHurtEvent event)
{
	EntityLivingBase e = event.getEntityLiving();
	if (!event.isCanceled() && CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this, 1, 2)))
	{
		float damageAmount = event.getAmount();
		DamageSource damageSrc = event.getSource();

		damageAmount = applyArmorCalculations(e, damageSrc, damageAmount);
		damageAmount = applyPotionDamageCalculations(e, damageSrc, damageAmount);
		damageAmount = Math.max(damageAmount - e.getAbsorptionAmount(), 0.0F);
		
		damageMedkit.put(e.getEntityId(), damageAmount);
		timesMedkit.put(e.getEntityId(), e.ticksExisted);
	}
}
 
Example #14
Source File: ItemCyberlimb.java    From Cyberware with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGH)
public void power(CyberwareUpdateEvent event)
{
	EntityLivingBase e = event.getEntityLiving();
	
	for (int i = 0; i < 4; i++)
	{
		ItemStack test = new ItemStack(this, 1, i);
		ItemStack installed = CyberwareAPI.getCyberware(e, test);
		if (e.ticksExisted % 20 == 0 && installed != null)
		{
			boolean used = CyberwareAPI.getCapability(e).usePower(installed, getPowerConsumption(installed));
			
			CyberwareAPI.getCyberwareNBT(installed).setBoolean("active", used);
		}
	}

}
 
Example #15
Source File: ItemCybereyes.java    From Cyberware with MIT License 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGH)
public void handleMissingEssentials(CyberwareUpdateEvent event)
{
	EntityLivingBase e = event.getEntityLiving();
			
	if (CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this)))
	{
		if (e.ticksExisted % 20 == 0)
		{
			boolean powerUsed = CyberwareAPI.getCapability(e).usePower(new ItemStack(this), getPowerConsumption(null));
			if (e.worldObj.isRemote && e == Minecraft.getMinecraft().thePlayer)
			{
				isBlind = !powerUsed;
			}
		}
	}
	else if (e.worldObj.isRemote && e == Minecraft.getMinecraft().thePlayer)
	{
		isBlind = false;
	}
	
}
 
Example #16
Source File: ItemCyberheart.java    From Cyberware with MIT License 6 votes vote down vote up
@SubscribeEvent(priority=EventPriority.HIGHEST)
public void power(CyberwareUpdateEvent event)
{
	EntityLivingBase e = event.getEntityLiving();
	ItemStack test = new ItemStack(this);
	if (e.ticksExisted % 20 == 0 && CyberwareAPI.isCyberwareInstalled(e, test))
	{
		if (!CyberwareAPI.getCapability(e).usePower(test, getPowerConsumption(test)))
		{
			e.attackEntityFrom(EssentialsMissingHandler.heartless, Integer.MAX_VALUE);
		}
	}
	
	if (CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this)))
	{
		e.removePotionEffect(MobEffects.WEAKNESS);
	}
}
 
Example #17
Source File: EventsClient.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onClientTickEvent(ClientTickEvent event) {
    Minecraft mc = Minecraft.getMinecraft();
    if (mc.world != null) {
        if (!mc.isGamePaused()) {
            WorldPhysObjectManager manager = ValkyrienSkiesMod.VS_PHYSICS_MANAGER
                .getManagerForWorld(mc.world);
            if (event.phase == Phase.END) {
                for (PhysicsWrapperEntity wrapper : manager.physicsEntities) {
                    wrapper.getPhysicsObject().onPostTickClient();
                }
                EntityDraggable.tickAddedVelocityForWorld(mc.world);
            }
        }
    }

}
 
Example #18
Source File: EventsClient.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST, receiveCanceled = true)
public void onDrawBlockHighlightEventFirst(DrawBlockHighlightEvent event) {
    GL11.glPushMatrix();
    BlockPos pos = Minecraft.getMinecraft().objectMouseOver.getBlockPos();
    Optional<PhysicsObject> physicsObject = ValkyrienUtils
        .getPhysicsObject(Minecraft.getMinecraft().world, pos);
    if (physicsObject.isPresent()) {
        RayTraceResult objectOver = Minecraft.getMinecraft().objectMouseOver;
        if (objectOver != null && objectOver.hitVec != null) {
            BufferBuilder buffer = Tessellator.getInstance().getBuffer();
            oldXOff = buffer.xOffset;
            oldYOff = buffer.yOffset;
            oldZOff = buffer.zOffset;

            buffer.setTranslation(-physicsObject.get()
                .getShipRenderer().offsetPos.getX(), -physicsObject.get()
                .getShipRenderer().offsetPos.getY(), -physicsObject.get()
                .getShipRenderer().offsetPos.getZ());
            physicsObject.get()
                .getShipRenderer()
                .applyRenderTransform(event.getPartialTicks());
        }
    }
}
 
Example #19
Source File: EventsClient.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST, receiveCanceled = true)
public void onDrawBlockHighlightEventLast(DrawBlockHighlightEvent event) {
    BlockPos pos = Minecraft.getMinecraft().objectMouseOver.getBlockPos();
    Optional<PhysicsObject> physicsObject = ValkyrienUtils
        .getPhysicsObject(Minecraft.getMinecraft().world, pos);
    if (physicsObject.isPresent()) {
        RayTraceResult objectOver = Minecraft.getMinecraft().objectMouseOver;
        if (objectOver != null && objectOver.hitVec != null) {
            BufferBuilder buffer = Tessellator.getInstance().getBuffer();
            buffer.xOffset = oldXOff;
            buffer.yOffset = oldYOff;
            buffer.zOffset = oldZOff;
            // wrapper.wrapping.renderer.inverseTransform(event.getPartialTicks());
            // objectOver.hitVec = RotationMatrices.applyTransform(wrapper.wrapping.coordTransform.lToWTransform, objectOver.hitVec);
        }
    }
    GL11.glPopMatrix();
}
 
Example #20
Source File: EventsCommon.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onWorldTickEvent(WorldTickEvent event) {
    // This only gets called server side, because forge wants it that way. But in case they
    // change their mind, this exception will crash the game to notify us of the change.
    if (event.side == Side.CLIENT) {
        throw new IllegalStateException("This event should never get called client side");
    }
    World world = event.world;
    switch (event.phase) {
        case START:
            PhysicsTickHandler.onWorldTickStart(world);
            break;
        case END:
            IHasShipManager shipManager = (IHasShipManager) world;
            shipManager.getManager().tick();
            PhysicsTickHandler.onWorldTickEnd(world);
            break;
    }
}
 
Example #21
Source File: EventsCommon.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onWorldLoad(WorldEvent.Load event) {
    World world = event.getWorld();
    event.getWorld().addEventListener(new VSWorldEventListener(world));
    IHasShipManager shipManager = (IHasShipManager) world;
    if (!event.getWorld().isRemote) {
        ValkyrienSkiesMod.VS_CHUNK_MANAGER.initWorld(world);
        shipManager.setManager(WorldServerShipManager::new);
    } else {
        shipManager.setManager(WorldClientShipManager::new);
    }
}
 
Example #22
Source File: PlayerInteractEventHandler.java    From AgriCraft with MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void denyBonemeal(PlayerInteractEvent.RightClickBlock event) {
    if (!event.getEntityPlayer().isSneaking()) {
        return;
    }
    ItemStack heldItem = event.getEntityPlayer().getActiveItemStack();
    if (!heldItem.isEmpty() && heldItem.getItem() == Items.DYE && heldItem.getItemDamage() == 15) {
        TileEntity te = event.getWorld().getTileEntity(event.getPos());
        if (te != null && (te instanceof TileEntityCrop)) {
            event.setUseItem(Event.Result.DENY);
        }
    }
}
 
Example #23
Source File: ForgeMain.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPlayerChangedWorld(EntityJoinWorldEvent event) {
    Entity entity = event.getEntity();
    if (!(entity instanceof EntityPlayerMP)) {
        return;
    }
    EntityPlayerMP player = (EntityPlayerMP) entity;
    if (player.worldObj.isRemote) {
        return;
    }
}
 
Example #24
Source File: ModToolLeveling.java    From TinkersToolLeveling with MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST, receiveCanceled = true)
public void onLivingHurt(LivingAttackEvent event) {
  // if it's cancelled it got handled by the battlesign (or something else. but it's a prerequisite.)
  if(!event.isCanceled()) {
    return;
  }
  if(event.getSource().isUnblockable() || !event.getSource().isProjectile() || event.getSource().getTrueSource() == null) {
    return;
  }
  // hit entity is a player?
  if(!(event.getEntity() instanceof EntityPlayer)) {
    return;
  }
  EntityPlayer player = (EntityPlayer) event.getEntity();
  // needs to be blocking with a battlesign
  if(!player.isActiveItemStackBlocking() || player.getActiveItemStack().getItem() != TinkerMeleeWeapons.battleSign) {
    return;
  }
  // broken battlesign.
  if(ToolHelper.isBroken(player.getActiveItemStack())) {
    return;
  }

  // at this point we duplicated all the logic if the battlesign should reflect a projectile.. bleh.
  int xp = Math.max(1, Math.round(event.getAmount()));
  addXp(player.getActiveItemStack(), xp, player);
}
 
Example #25
Source File: EventManager.java    From Logistics-Pipes-2 with MIT License 5 votes vote down vote up
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onTick(TickEvent.ClientTickEvent event) {
	if(event.side == Side.CLIENT) {
		ticks++;
		ClientProxy.particleRender.updateParticles();
	}
}
 
Example #26
Source File: BiomeGeneratorImplementation.java    From malmo with MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onBiomeGenInit(WorldTypeEvent.InitBiomeGens event) {
	// Negative one is flag value for normal world gen
	if (bparams.getBiome() == -1)
		return;
	GenLayer[] replacement = new GenLayer[2];
	replacement[0] = new GenLayerConstant(bparams.getBiome());
	replacement[1] = replacement[0];
	event.setNewBiomeGens(replacement);
}
 
Example #27
Source File: ForgeMain.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerQuit(PlayerEvent.PlayerLoggedOutEvent event) {
    if (event.player.worldObj.isRemote) {
        return;
    }
    handleQuit((EntityPlayerMP) event.player);
}
 
Example #28
Source File: EventsCommon.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onWorldUnload(WorldEvent.Unload event) {
    if (!event.getWorld().isRemote) {
        ValkyrienSkiesMod.VS_CHUNK_MANAGER.removeWorld(event.getWorld());
    } else {
        // Fixes memory leak; @DaPorkChop please don't leave static maps lying around D:
        lastPositions.clear();
    }
    ValkyrienSkiesMod.VS_PHYSICS_MANAGER.removeWorld(event.getWorld());
    IHasShipManager shipManager = (IHasShipManager) event.getWorld();
    shipManager.getManager().onWorldUnload();
}
 
Example #29
Source File: PlayerInteractEventHandler.java    From AgriCraft with MIT License 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public static void waterPadCreation(PlayerInteractEvent.RightClickBlock event) {
    // Fetch held item.
    final ItemStack stack = event.getItemStack();

    // Check if holding shovel.
    if (!StackHelper.isValid(stack, ItemSpade.class)) {
        return;
    }

    // Fetch world information.
    final BlockPos pos = event.getPos();
    final World world = event.getWorld();
    final IBlockState state = world.getBlockState(pos);

    // Fetch the block at the location.
    final Block block = state.getBlock();

    // Test that clicked block was farmland.
    if (block != Blocks.FARMLAND) {
        return;
    }

    // Deny the event.
    event.setUseBlock(Event.Result.DENY);
    event.setUseItem(Event.Result.DENY);
    event.setResult(Event.Result.DENY);

    // If we are on the client side we are done.
    if (event.getSide().isClient()) {
        return;
    }

    // Fetch the player.
    final EntityPlayer player = event.getEntityPlayer();

    // Create the new block on the server side.
    world.setBlockState(pos, AgriBlocks.getInstance().WATER_PAD.getDefaultState(), 3);

    // Damage player's tool if not in creative.
    if (!player.capabilities.isCreativeMode) {
        stack.damageItem(1, player);
    }
}
 
Example #30
Source File: EventsCommon.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onBlockBreakFirst(BlockEvent event) {
    BlockPos pos = event.getPos();
    Chunk chunk = event.getWorld()
        .getChunk(pos);
    IPhysicsChunk physicsChunk = (IPhysicsChunk) chunk;
    if (physicsChunk.getPhysicsObjectOptional()
        .isPresent()) {
        event.setResult(Result.ALLOW);
    }
}