Diego Francisco
Diego Francisco

Reputation: 1910

Minecraft Forge - Place block onItemUse

I'm trying to make my custom item place water when used:

public class Beaker extends Item implements IHasModel {
  public Beaker(String name, CreativeTabs tab, int maxStackSize) {
    setUnlocalizedName(name);
    setRegistryName(name);
    setCreativeTab(tab);
    setMaxStackSize(maxStackSize);

    ItemInit.ITEMS.add(this);
  }

  @Override
  public void registerModels() {
    Main.proxy.registerItemRenderer(this, 0, "inventory");
  }

  @Override
  public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
    BlockPos clickedBlock = new BlockPos(hitX, hitY, hitZ);
    worldIn.setBlockState(clickedBlock, Blocks.WATER.getDefaultState());
    return EnumActionResult.SUCCESS;
  }
}

However, when I right click, the item gets used (animation plays) but the water is not placed, I'm using Minecraft 1.12.2 and Forge 14.23.2.2613.

Upvotes: 0

Views: 4964

Answers (1)

hitX hitY and hitZ have no relation to the world location where the action was performed. They are partial values within the clicked block for performing actions based on where the block was clicked (e.g. which button on a number pad).

If we look at ItemBlockSpecial (which handles items like Cake, Repeaters, Brewing Stands, and Cauldrons) we find this code:

public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
    IBlockState iblockstate = worldIn.getBlockState(pos);
    Block block = iblockstate.getBlock();

    // snow layer stuff we don't care about
    if (!block.isReplaceable(worldIn, pos))
    {
        pos = pos.offset(facing);
    }
    // placement code
}

The important thing to note here is that the pos parameter is used directly, while being modified by the facing parameter in the event that the block clicked is not replaceable (e.g. Tall Grass is replaceable, Stone is not).

If ItemBlockSpecial isn't sufficient for you (i.e. you can't make your item an instance of ItemBlockSpecial), then the code it uses to do things probably still will be.

Upvotes: 1

Related Questions