Overriding Item Logic

With LibMinecraft, you can easily override the logic of a single block or item. This tutorial only applies to servers. In this example, we will make placing coal ore turn into gold ore, and we'll make using a gold ingot on a block turn it into a gold block. First, you need to know how items and blocks work in LibMinecraft.

Each block and each item has its own unique class. This class contains the block or item ID and all logic for that block or item. These classes can be very simple, like DirtBlock, or very complex, like DoorBlock. However, for the sake of memory, block and item objects are never stored in memory. Instead, Blocks may be implicitly cast to and from bytes, and the same is true of Items for shorts. World.GetBlock also returns a Block with all of the appropriate metadata, and inventory slots do the same.

To actually override a block or item in LibMinecraft, use the Block.OverrideBlock and Item.OverrideItem methods. Each one accepts an instance of your override class to use for all instances of that block or item in LibMinecraft. Our custom classes will be called CoalOreBlockCustom and GoldIngotItemCustom, in this tutorial. Therefore, the code to override LibMinecraft's use of each would be this:

Code (C#): Specifying your overrides

Block.OverrideBlock(new CoalOreBlockCustom());
Item.OverrideItem(new GoldIngotItemCustom());

The actual code for these classes is simple:

Code (C#): Override classes

public class CoalOreBlockCustom : CoalOreBlock
	public override bool BlockPlaced(World world, Vector3 position,
                      Vector3 blockClicked, byte facing, Entity placedBy)
		// Place gold instead
		world.SetBlock(position, new GoldOreBlock());
		// Return false to disallow normal placement
		return false;

public class GoldIngotItemCustom : GoldIngotItem
	public override void PlayerUseItem(World world, PlayerEntity player, 
                      Vector3 location, Vector3 targetBlock, byte facing)
                // Turn the block clicked into gold
		world.SetBlock(targetBlock, new GoldBlock());

PlayerUseItem is the only available override on the Item classes. Blocks have more:

  • BlockPlaced
  • BlockDestroyed
  • BlockRightClicked
  • BlockUpdate
  • ScheduledUpdate

Last edited Feb 24, 2012 at 10:24 PM by sircmpwn, version 7


No comments yet.