User Tools

Site Tools


tutorial:blocks

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorial:blocks [2020/06/14 00:17] – more formatting fixes + highlights draylartutorial:blocks [2023/11/18 08:34] (current) solidblock
Line 1: Line 1:
 ====== Adding a Block ====== ====== Adding a Block ======
  
-==== Introduction ====+Adding blocks to your mod follows a similar process to [[tutorial:items|adding an item]]. You can create an instance of ''Block'' or a custom class, and then register it under ''Registries.BLOCK'' (for 1.19.3 and above) or ''Registry.BLOCK'' (for 1.19.2 and below). You also need to provide a texture and blockstate/model file to give your block visuals. For more information on the block model format, view the [[https://minecraft.wiki/Model|Minecraft Wiki Model page]].
  
-To add block to your mod, you will need to register a new instance of the Block class. For more control over your block, you can create a custom block class. We'll also look at adding a block model. +===== Creating a Block =====
  
-==== Creating a Block ====+Start by creating an instance of ''Block''. It can be stored at any location, but we will start at the top of your ''ModInitializer''. The ''Block'' constructor requires an ''AbstractBlock.Settings'' instance, which is a builder for configuring block properties. Fabric provides a ''FabricBlockSettings'' builder class with more available options.
  
-To start, create an instance of Block in your main mod class. Block's constructor uses the FabricBlockSettings builder to set up basic properties of the block, such as hardness and resistance: 
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 public class ExampleMod implements ModInitializer { public class ExampleMod implements ModInitializer {
  
-    // an instance of our new block +    /* Declare and initialize our custom block instance
-    public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL)); +       We set our block material to `METAL`. 
-    +        
 +       `strength` sets both the hardness and the resistance of a block to the same value. 
 +       Hardness determines how long the block takes to break, and resistance determines how strong the block is against blast damage (e.g. explosions). 
 +       Stone has a hardness of 1.5f and a resistance of 6.0f, while Obsidian has a hardness of 50.0f and a resistance of 1200.0f. 
 +        
 +       You can find the stats of all vanilla blocks in the class `Blocks`, where you can also reference other blocks. 
 +    */ 
 +    // public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL).strength(4.0f)); // fabric api version <= 0.77.0 
 +    public static final Block EXAMPLE_BLOCK  = new Block(FabricBlockSettings.create().strength(4.0f));
     @Override     @Override
     public void onInitialize() {     public void onInitialize() {
Line 21: Line 28:
 </code> </code>
  
-==== Registering Block ====+==== Registering your Block ==== 
 + 
 +Blocks should be registered under the ''Registries.BLOCK'' registry. Call ''Registry.//register//'' and pass in the appropriate arguments. You can either register the block in ''onInitialize'' method or directly when creating the block instance in the static context, as the ''register'' method returns the block instance as well.
  
-Registering blocks is the same as registering itemsCall //Registry.register// and pass in the appropriate arguments.+If you're using version 1.19.2 or below, please replace ''Registries.BLOCK'' with ''Registry.BLOCK''
  
-<code java [enable_line_numbers="true",highlight_lines_extra="8"]>+<code java [enable_line_numbers="true",highlight_lines_extra="11"]>
 public class ExampleMod implements ModInitializer { public class ExampleMod implements ModInitializer {
  
-    // an instance of our new block +    // public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL).strength(4.0f)); // fabric api version <= 0.77.0 
-    public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL));+    public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.create().strength(4.0f));
          
     @Override     @Override
     public void onInitialize() {     public void onInitialize() {
-        Registry.register(Registry.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK);+        Registry.register(Registries.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK);
     }     }
 } }
 </code> </code>
  
-Your block will //not// be accessible as an item, but it can be seen in-game by using ''/setblock tutorial:example_block.''+Your custom block will //not// be accessible as an item yet, but it can be seen in-game by using the command ''/setblock <position> tutorial:example_block''.
  
-==== Registering a BlockItem ====+==== Registering an Item for your Block ====
  
-In most cases, you want to be able to place your block using an item. To do this, you need to register a corresponding BlockItem in the item registry. You can do this by registering an instance of BlockItem under Registry.ITEM. The registry name of the item should usually be the same as the registry name of the block.+In most cases, you want to be able to place your block using an item. To do this, you need to register a corresponding BlockItem in the item registry. You can do this by registering an instance of BlockItem under ''Registries.ITEM''. The registry name of the item should usually be the same as the registry name of the block.
  
-<code java [enable_line_numbers="true",highlight_lines_extra="9"]>+<code java [enable_line_numbers="true",highlight_lines_extra="12"]>
 public class ExampleMod implements ModInitializer { public class ExampleMod implements ModInitializer {
  
-    // an instance of our new block +    // public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL).strength(4.0f)); // fabric api version <= 0.77.0 
-    public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL));+    public static final Block EXAMPLE_BLOCK  = new Block(FabricBlockSettings.create().strength(4.0f));
          
     @Override     @Override
     public void onInitialize() {     public void onInitialize() {
-        Registry.register(Registry.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK); +        Registry.register(Registries.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK); 
-        Registry.register(Registry.ITEM, new Identifier("tutorial", "example_block"), new BlockItem(EXAMPLE_BLOCK, new Item.Settings().group(ItemGroup.MISC)));+        Registry.register(Registries.ITEM, new Identifier("tutorial", "example_block"), new BlockItem(EXAMPLE_BLOCK, new FabricItemSettings()));
     }     }
 } }
 </code> </code>
  
-==== Giving your block a model ====+===== Giving your Block Visuals =====
  
-As you probably have noticedthe block is simply a purple and black checkerboard pattern in-game. This is Minecraft's way of showing you that the block has no modelModeling a block is a little bit more difficult than modeling an item. You will need three files: A blockstate file, a block model file, and an item model file if the block has a BlockItemTextures are also required if you don't use vanilla ones. The files should be located here:+At this pointyour new block will appear as a purple and black checkerboard pattern in-game. This is Minecraft's way of showing you that something went wrong while loading the block's assets (or visuals)A full list of issues will be printed to your log when you run your client. You will need these files to give your block visuals: 
 +  * A blockstate file 
 +  * A block model file 
 +  * A texture 
 +  * An item model file (if the block has an item associated with it).
  
-  Blockstatesrc/main/resources/assets/tutorial/blockstates/example_block.json +The files should be located here:
-  Block Model: src/main/resources/assets/tutorial/models/block/example_block.json +
-  Item Model: src/main/resources/assets/tutorial/models/item/example_block.json +
-  Block Texture: src/main/resources/assets/tutorial/textures/block/example_block.png+
  
-The blockstate file determines which model that the block should use depending on it'blockstate. As our block has only one statethe file is a simple as this:+  * Blockstate: ''src/main/resources/assets/tutorial/blockstates/example_block.json'' 
 +  * Block Model: ''src/main/resources/assets/tutorial/models/block/example_block.json'' 
 +  * Item Model: ''src/main/resources/assets/tutorial/models/item/example_block.json'' 
 +  * Block Texture: ''src/main/resources/assets/tutorial/textures/block/example_block.png'' 
 + 
 +The blockstate file determines which model block should use depending on its blockstate. Our block doesn't have any potential statesso we cover everything with ''""''
  
 <code JavaScript src/main/resources/assets/tutorial/blockstates/example_block.json> <code JavaScript src/main/resources/assets/tutorial/blockstates/example_block.json>
Line 77: Line 92:
 </code> </code>
  
-The block model file defines the shape and texture of your block. We will use block/cube_all, which will allow us to easily set the same texture on all sides of the block.+The block model file defines the shape and texture of your block. Our model will have ''block/cube_all''as a parent, which applies the texture ''all'' to //all// sides of the block.
  
 <code JavaScript src/main/resources/assets/tutorial/models/block/example_block.json> <code JavaScript src/main/resources/assets/tutorial/models/block/example_block.json>
Line 88: Line 103:
 </code> </code>
  
-In most cases you want the block to look the same in handTo do this, you can make an item file that inherits from the block model file:+In most casesyou will want the block to look the same in item formYou can make an item model that has the block model file as a parent, which makes it appear exactly like the block:
  
 <code JavaScript src/main/resources/assets/tutorial/models/item/example_block.json> <code JavaScript src/main/resources/assets/tutorial/models/item/example_block.json>
Line 96: Line 111:
 </code> </code>
  
-Load up Minecraft and your block should finally have a texture!+Load up Minecraft and your block should have visuals!
  
-==== Adding a block loot table ====+===== Configuring Block Drops =====
  
-The block must have a loot table for any items to drop when the block is broken. Assuming you have created an item for your block and registered it using the same name as the block, the following file will produce regular block drops ''src/main/resources/data/tutorial/loot_tables/blocks/example_block.json''.+To make your block drop items when brokenyou will need a //loot table//. The following file will cause your block to drop its respective item form when broken: 
  
 <code JavaScript src/main/resources/data/tutorial/loot_tables/blocks/example_block.json> <code JavaScript src/main/resources/data/tutorial/loot_tables/blocks/example_block.json>
Line 124: Line 139:
 </code> </code>
  
-When broken in survival mode, the block will now drop an item.+The condition ''minecraft:survives_explosion'' means thatif the block is destroyed in an explosion with decay (such as creeper explosion, not TNT explosion), it //may not// drop. If there is no this condition, the block always drops in explosions with decay.
  
-==== Creating Custom Block Class ====+In minecraft 1.17, there has been change for breaking blocks. Now, to define harvest tools and harvest levels, we need to use tags. Read about tags at: [[tutorial:tags|Tags Tutorial]]. The tags that we need to add the block to are:
  
-When creating a simple block the above approach works wellbut sometimes you want a //special// block with unique mechanics. We'll create a separate class that extends Block to do this. The class needs a constructor that takes in a BlockSettings argument.+ * Harvest tool: ''src/main/resources/data/minecraft/tags/blocks/mineable/<tooltype>.json'', where ''<tooltype>'' can be any of: ''axe'', ''pickaxe'', ''shovel'' or ''hoe'' 
 + * Harvest level: ''src/main/resources/data/minecraft/tags/blocks/needs_<tier>_tool.json'', where ''<tier>'' can be any of: ''stone'', ''iron'' or ''diamond'' (//not including// ''netherite''
 + 
 +<code JavaScript src/main/resources/data/minecraft/tags/blocks/mineable/pickaxe.json> 
 +
 +  "replace": false, 
 +  "values":
 +    "tutorial:example_block" 
 +  ] 
 +
 +</code> 
 + 
 +<code JavaScript src/main/resources/data/minecraft/tags/blocks/needs_stone_tool.json> 
 +
 +  "replace": false, 
 +  "values":
 +    "tutorial:example_block" 
 +  ] 
 +
 +</code> 
 + 
 +For the harvest level tags (''needs_stone_tool'', ''needs_iron_tool'' and ''needs_diamond_tool'') to take effect, add ''requiresTool()'' to the FabricBlockSettings in the block declaration: 
 + 
 +<code java [enable_line_numbers="true"]> 
 +    // public static final Block EXAMPLE_BLOCK = new ExampleBlock(FabricBlockSettings.of(Material.METAL).strength(4.0f).requiresTool()); // fabric api version <= 0.77.0 
 +    public static final Block EXAMPLE_BLOCK = new ExampleBlock(FabricBlockSettings.create().strength(4.0f).requiresTool()); 
 +</code> 
 + 
 +===== Creating a Custom Block Class ===== 
 + 
 +The above approach works well for simple blocks but falls short when you want a block with //unique// mechanics. We'll create a //separate// class that extends ''Block'' to do this. The class needs a constructor that takes in an ''AbstractBlock.Settings'' argument:
  
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
Line 139: Line 184:
 </code> </code>
  
-Just like we did in the item tutorial, you can override methods in the block class for custom functionality.+You can override methods in the block class for custom functionality. Here's an implementation of the ''onUse'' method, which is called when you right-click the block. We check if the interaction is occurring on the server, and then send the player a message saying, //"Hello, world!"//
  
-If you want your block to be transparent, in your client mod initializer code, do: +<code java [enable_line_numbers="true",highlight_lines_extra="8,9,10,11,12,13,14,15"]
-<code java> +public class ExampleBlock extends Block {
-    BlockRenderLayerMap.INSTANCE.putBlock(EXAMPLE_BLOCK, RenderLayer.getTranslucent()); +
-</code>+
  
-In versions before 1.15/Blaze3D, you override a method in Block class instead:+    public ExampleBlock(Settings settings) { 
 +        super(settings); 
 +    }
  
-<code java> 
-    @Environment(EnvType.CLIENT) 
     @Override     @Override
-    public BlockRenderLayer getRenderLayer() { +    public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) { 
-        return BlockRenderLayer.TRANSLUCENT;+        if (!world.isClient) { 
 +            player.sendMessage(Text.literal("Hello, world!"), false); 
 +        } 
 + 
 +        return ActionResult.SUCCESS;
     }     }
 +}
 </code> </code>
  
-To add this block into the game, replace //new Block// with //new ExampleBlock// when you register it.+To use your custom block class, replace ''new Block'' with ''new ExampleBlock'':
  
-<code java [enable_line_numbers="true"]>+<code java [enable_line_numbers="true",highlight_lines_extra="3"]>
 public class ExampleMod implements ModInitializer { public class ExampleMod implements ModInitializer {
  
-    // an instance of our new block +    // public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.of(Material.METAL).strength(4.0f)); // fabric api version <= 0.77.0 
-    public static final ExampleBlock EXAMPLE_BLOCK = new ExampleBlock(Block.Settings.of(Material.STONE));+    public static final Block EXAMPLE_BLOCK = new Block(FabricBlockSettings.create().strength(4.0f));
          
     @Override     @Override
     public void onInitialize() {     public void onInitialize() {
-        Registry.register(Registry.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK); +        Registry.register(Registries.BLOCK, new Identifier("tutorial", "example_block"), EXAMPLE_BLOCK); 
-        Registry.register(Registry.ITEM, new Identifier("tutorial", "example_block"), new BlockItem(EXAMPLE_BLOCK, new Item.Settings().group(ItemGroup.MISC)));+        Registry.register(Registries.ITEM, new Identifier("tutorial", "example_block"), new BlockItem(EXAMPLE_BLOCK, new Item.Settings()));
     }     }
 } }
 </code> </code>
  
-Your custom block should now be transparent!+==== Custom Shape====
  
- +When using block models that do not //entirely// fill the block (eg. Anvil, Slab, Stairs), while its voxel shape is full, the hidden faces of the adjacent blocks will be exposed:
-==== Custom VoxelShape ==== +
- +
-When making custom blocks that do not entirely fill the block, the adjacent blocks might hide their faces. In this case of a custom vertical slab it would look like this:+
  
 {{:tutorial:voxelshape_wrong.png?200|}} {{:tutorial:voxelshape_wrong.png?200|}}
  
 +To fix this, we have to define the ''VoxelShape'' of the new block:
  
-We have to define the VoxelShape of the new block into one which is not an entire block: +<code java
- +public class ExampleBlock extends Block { 
-<code> +    [...] 
-@Override +    @Override 
- public VoxelShape getOutlineShape(BlockState state, BlockView view, BlockPos pos, EntityContext ctx) { +    public VoxelShape getOutlineShape(BlockState state, BlockView view, BlockPos pos, ShapeContext context) { 
-     return VoxelShapes.cuboid(0f, 0f, 0f, 1f, 1.0f, 0.5f); +        return VoxelShapes.cuboid(0f, 0f, 0f, 1f, 1.0f, 0.5f); 
- }+    } 
 +}
 </code> </code>
- 
-By doing so we also define getCollisionShape, because by default it returns the result of OutlineShape. 
  
 {{:tutorial:voxelshape_fixed.png?200|}} {{:tutorial:voxelshape_fixed.png?200|}}
  
-==== Next Steps ====+You can also define other types of shapes for the block. The type of shapes of blocks include: 
 +  * **outline shape**: the shape used as default value for most type of shapes. In the worlds, when you points to the shape, the translucent black outline is displayed according to this shape. Most times it should not be empty. 
 +  * **collision shape**: the shape used to calculate collisions. When entities (including players) are moving, their collision box usually cannot intersect the collision shape of blocks. Some blocks, such as fences and walls, may have a collision shape higher than one block. Some blocks, such as flowers, have an empty collision shape. Apart from modifying ''getCollisionShape'' method, you can also call ''noCollision'' in the ''FabricBlockSettings'' when creating the block. 
 +  * **raycasting shape**: the shape used to calculate raycasting (the process judging which block you are pointing to). You usually do not need to specify it. 
 +  * **camera collision shape**: the shape used to calculate the position of camera in third-party view. Glass and powder snow have an empty camera collision shape. 
 + 
 +===== Next Steps =====
 [[tutorial:blockstate|Adding simple state to a block, like ints and booleans]].  [[tutorial:blockstate|Adding simple state to a block, like ints and booleans]]. 
  
 [[tutorial:blockentity|Giving blocks a block entity so they can have advanced state like inventories]]. Also needed for many things like GUI and custom block rendering. [[tutorial:blockentity|Giving blocks a block entity so they can have advanced state like inventories]]. Also needed for many things like GUI and custom block rendering.
 +
 +To make your block flammable (that is, can be burned in fire), you may use ''FlammableBlockRegistry''.
tutorial/blocks.1592093861.txt.gz · Last modified: 2020/06/14 00:17 by draylar