Forge Lesson 02 – Creating a block

In lesson two we are going to add a block, which if right clicked will spawn a sheep. We will continue with the workspace from last time in which we created an item which spawns pigs. You can download the code at the end of the previous lesson

We will start with creating a new class named BlockSpawn in the noppes.tutorials package and make it extend the Block class.

package noppes.tutorials;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

public class BlockSpawn extends Block{

	public BlockSpawn() {
		super(Material.rock);
	}
}

Next we need to create a new BlockSpawn object and register the block in the GameRegistry in the Tutorial class init function.

Block spawn = new BlockSpawn().setBlockName("tutorial_spawn").setCreativeTab(CreativeTabs.tabTools);
GameRegistry.registerBlock(spawn, "tutorial_spawn");

Run minecraft and you will see the block in the tools creative tab. Again it will have no texture and no name.

You can give it a name like with the item by adding the following line to your en_US.lang

tile.tutorial_spawn.name=Tutorial Block

Now to fix the texture you will need to create a new package: assets.tutorial.textures.blocks and download the block texture or create your own and put it in the package. To point the block texture to the correct location call setTextureName with a string containing the modid:texturename

Block spawn = new BlockSpawn().setBlockName("tutorial_spawn").
    setBlockTextureName("tutorial:spawn").setCreativeTab(CreativeTabs.tabTools);

If you run minecraft again the name and the texture should display correctly.

Blocks have an onBlockActivated functions which is called when a player right clicks a block. To make the block spawn sheep we will need to overwrite that function.

@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9){
	if(!world.isRemote){
		EntitySheep sheep = new EntitySheep(world);
		sheep.setPosition(x + 0.5, y + 1, z + 0.5);
		//gives the sheep a random color
		sheep.setFleeceColor(world.rand.nextInt(16));
		world.spawnEntityInWorld(sheep);
	}
	return true;
}

Just like with the item we dont want it to spawn client side otherwise it will ghost. To give it a random color we use world.rand.nextInt(16) is for. That gives a random integer between 0 and 16 not including 16 itself.

Note: In 1.6 setBlockName used to be setUnlocalizedName and setBlockTextureName use to be setTextureName. Basically the same as with Item. I wouldn’t be surprised if mcp changes it back in the future.

Download the Code