Jump to content

[1.9.4] Deleting a block in the world, and dropping items where that block was?


Recommended Posts

Posted

Hello,

I've been making a new item that I'm planning on making to delete log blocks, and replace it with at least 6 plank blocks of that kind of wood. So far, it's got the shovel code (i.e. turn grass into paths) as a placeholder right click event. What could I use to make this item do what I want? Thanks if you can help.

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

Ok, how would I drop the item at the block's posistion? I'm not sure which call would spawn an item entity.

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

I added that line into the code, but now it seems to not destroy the block in the world.

Here's my code:

 

package com.t10a.minedran.item.tools;

import com.t10a.minedran.reference.Reference;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class ItemHandsaw extends Item
{
private final Item.ToolMaterial material;

public ItemHandsaw(ToolMaterial material)
{
	this.material = material;
	this.setMaxStackSize(1);
	this.setMaxDamage(material.getMaxUses());
	this.setCreativeTab(CreativeTabs.TOOLS);
	this.setUnlocalizedName(Reference.ItemBase.HANDSAW.getUnlocalizedName() + "_" + getToolMaterialName().toLowerCase());
	this.setRegistryName(Reference.ItemBase.HANDSAW.getRegistryName()  + "_" + getToolMaterialName().toLowerCase());
}

public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float x, float y, float z)
    {
        if (!playerIn.canPlayerEdit(pos.offset(facing), facing, stack))
        {
            return EnumActionResult.FAIL;
        }
        else
        {
            IBlockState iblockstate = worldIn.getBlockState(pos);
            Block block = iblockstate.getBlock();

            if (facing != EnumFacing.DOWN && worldIn.getBlockState(pos.up()).getMaterial() == Material.AIR && block == Blocks.LOG)
            {
            	worldIn.destroyBlock(new BlockPos(x,y,z), true);
                worldIn.playSound(playerIn, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS, 1.0F, 1.0F);

                if (!worldIn.isRemote)
                {
                    stack.damageItem(1, playerIn);
                }

                return EnumActionResult.SUCCESS;
            }
            else
            {
                return EnumActionResult.PASS;
            }
        }
    }    

public String getToolMaterialName()
    {
        return this.material.toString();
    }
    
    public int getItemEnchantability()
    {
        return this.material.getEnchantability();
    }
    
    public boolean getIsRepairable(ItemStack toRepair, ItemStack repair)
    {
        ItemStack mat = this.material.getRepairItemStack();
        if (mat != null && net.minecraftforge.oredict.OreDictionary.itemMatches(mat, repair, false)) return true;
        return super.getIsRepairable(toRepair, repair);
    }
}

 

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

The three

float

arguments of

Item#onItemUse

are where the player clicked on the block. The block's position in the world is given to you as the

BlockPos

argument.

 

Always annotate override methods with

@Override

so you get a compilation error if they don't actually override a super method.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Okay, it works and it drops the log block. How would I check for the type of log, and drop the corresponding plank blocks in a specific amount?

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

Use

World#getBlockState

to get the

IBlockState

at the specified position. Use

IBlockState#getBlock

to get the

Block

represented by the

IBlockState

.

 

If you only want to handle vanilla logs, check if the

Block

is

Blocks.LOG

or

Blocks.LOG2

. If it is, use

IBlockState#getValue

to get the value of the

BlockOldLog.VARIANT

property (if it's

Blocks.LOG

) or the

BlockNewLog.VARIANT

property (if it's

Blocks.LOG2

). This will give you a

BlockPlanks.EnumType

value.

 

You can then create an

ItemStack

of

Blocks.PLANKS

, using the value returned by

BlockPlanks.EnumType#getMetadata

as the metadata. To drop this in the world, use

Block.spawnAsEntity

.

 

Handling modded logs will be a bit trickier because there's no easy and reliable way to know what the corresponding planks are. You can use

Block#isWood

to check if a block is a log.

 

To get the corresponding planks, you can either:

  • Assume that a single log in the crafting grid will result in planks (which may or may not be the case): Create an
    InventoryCrafting

    with a dummy

    Container

    , put an

    ItemStack

    of the logs in it and use

    CraftingManager#findMatchingRecipe

    to get the resulting planks

    ItemStack

    .

    • Pros: Has the potential to work for any mod without having to explicitly add support. Cons: Not guaranteed to work for all mods.

     

     

     

    [*]Create a class to hold the log to plank conversion recipes (similar to

    FurnaceRecipes

    ), register a recipe for each vanilla log and then use this in

    ItemHandsaw

    . You can then add recipes for other mods' logs as needed.

    • Pros: Guaranteed to work for any mod you've added support for. Cons: Only works for mods you've explicitly added support for.

     

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Ok, I'm interested in creating a log to plank recipe class. How would I get started with that?

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

I think the best way to implement this is to have your recipe class store a

Map<Block, Function<IBlockState, ItemStack>>

. You can then have a method that takes an

IBlockState

, looks up the

Function

in the

Map

using the

Block

, calls the

Function

with the

IBlockState

and returns the resulting

ItemStack

. Return

null

if there's no

Function

for the specified

Block

.

 

You can then call this method in

ItemHandsaw#onItemUse

. If it returns a non-

null

value, set the block to air and drop the

ItemStack

in the world.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Okay, I'm starting to make the class. After trying to emulate the furnace recipe class, I've gotten this so far (I know, it won't work. This is as far as I've gone before I start getting lost in what to change to make it work)

 

package com.t10a.minedran.item.crafting;

import net.minecraft.item.ItemStack;

import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Nullable;

import com.google.common.base.Function;

import net.minecraft.block.Block;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;

public class HandsawRecipes
{
private Map<Block, Function<IBlockState, ItemStack>> handsawList = Maps.<Block, Function<IBlockState, ItemStack>>newHashMap();

private HandsawRecipes(Block input, IBlockState iblockstate, Function<IBlockState, ItemStack> planks)
    {
	this.addHandsawRecipe(input, iblockstate, planks);
    }

    public void addHandsawRecipe(Block input, IBlockState iblockstate, Function<IBlockState, ItemStack> planks)
    {
        if (getSmeltingResult(input) != null) { net.minecraftforge.fml.common.FMLLog.info("Ignored handsaw recipe with conflicting input: " + input + " = " + planks); return; }
        this.handsawList.put(input, planks);
    }
    
    @Nullable
    public ItemStack getSmeltingResult(Block input)
    {
        for (Entry<Block, Function<IBlockState, ItemStack>> entry : this.handsawList.entrySet())
        {
            if (this.compareItemStacks(input, (Block)entry.getKey()))
            {
                return (ItemStack)entry.getValue();
            }
        }

        return null;
    }
    
    private boolean compareItemStacks(Block input, Block output)
    {
        return output.getBlockState() == input.getBlockState();
    }
    
    public Map<Block, Function<IBlockState, ItemStack>> getSmeltingList()
    {
        return this.handsawList;
    }
}

 

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

The only methods you need in

HandsawRecipes

are the following:

 


  • void addHandsawRecipe(Block, Function<IBlockState, ItemStack>)


    • Get the
      Function

      for the

      Block

      from the

      Map

      .

    • If it exists, log or throw an error. If it doesn't, add the
      Function

      argument to the

      Map

      .

     

     

     

    [*]

    @Nullable ItemStack geResult(IBlockState)

    • Get the
      IBlockState

      's

      Block

      , then get the

      Function

      for that

      Block

      from the

      Map

      .

    • If there's no
      Function

      , return

      null

      . If there is a

      Function

      , call

      Function#apply

      with the

      IBlockState

      and return the resulting

      ItemStack

      .

     

 

If you're going to use a singleton instance like

FurnaceRecipes

does, you'll also need an instance field and a static method to get the instance.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Okay, I cleaned up the code, and I'm now getting a syntax error of 'Syntax error, insert "... VariableDeclaratorId" to complete FormalParameter' with Block & IBlockState, as well as Eclipse wanting to take out a bunch of brackets.

 

Here's what I've cleaned up and tweaked so far:

 

package com.t10a.minedran.item.crafting;

import java.util.Map;

import javax.annotation.Nullable;

import com.google.common.base.Function;
import com.google.common.collect.Maps;

import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;


public class HandsawRecipes
{
private static final HandsawRecipes HANDSAW_RECIPES = new HandsawRecipes();
private Map<Block, Function<IBlockState, ItemStack>> handsawList = Maps.<Block, Function<IBlockState, ItemStack>>newHashMap();

public static HandsawRecipes instance()
    {
        return HANDSAW_RECIPES;
    }

    public HandsawRecipes() 
    {

}
    
    public void addHandsawRecipe(Block, Function<IBlockState, ItemStack>)
    {
    	
    }
    
    @Nullable 
    public ItemStack geResult(IBlockState)
    {
    	for (Entry<ItemStack, ItemStack> entry : this.handsawList.entrySet())
        {
            if (this.compareItemStacks(stack, (ItemStack)entry.getKey()))
            {
                return (ItemStack)entry.getValue();
            }
        }
        return null;
    }
}

 

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Posted

The method signatures I posted aren't valid Java themselves, they're using an abbreviated notation without the parameter names.

 

You weren't meant to blindly copy-paste them.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

Sorry about that... I'm not familiar with Functions<> and creating custom recipe handlers.

But I'm learning along the way.

If I'm asking a whole bunch of questions, please don't get angry. I'm trying to learn.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I need to know what mod is doing this crash, i mean the mod xenon is doing the crash but i want to know who mod is incompatible with xenon, but please i need to know a solution if i need to replace xenon, i cant use optifine anymore and all the other mods i tried(sodium, lithium, vulkan, etc) doesn't work, it crash the game.
    • I have been trying to solve a consistent crashing issue on my brother's computer where it will crash during the "Scanning Mod Candidates" phase of the loading process that starts when you click the play button on the Minecraft launcher. The issue seems to stem from a missing library that it mentions in the log file I provide below. I might I'm missing the bigger issue here for a smaller one but hopefully someone can find what I'm missing. Here's all of the stuff that I've been able to figure out so far: 1. It has nothing to do with mods, the crash happened with a real modpack, and even when I made a custom modpack and launched it without putting ANY mods into it (That is where the log file comes from by the way). 2. I have tried to find this class like a file in the Minecraft folders, but I've had no luck finding it (I don't think it works like that, but since I really don't understand how it works, I just figured I'd try). 3. I haven't seen anyone else have this issue before. 4. I know that my modpack (with mods) does work since I've run it on my computer, and it works fantastic. For some reason my brother's computer can't seem to run anything through curseforge. 5. This is for Minecraft version 1.20.1, Minecraft launcher version 3.4.50-2.1.3, forge 47.3.0, and curseforge app version 1.256.0.21056 6. My brother is using a Dell laptop from 6 years ago running Windows 10 (If you think more info on this would help, please ask as I do have it. I'm just choosing not to put it here for now). 7. I have reinstalled the curseforge app and installed Minecraft version 1.20.1. I have not reinstalled Minecraft or forge 47.3.0 but I didn't know if that would help. 8. I had an error code of 1 Please let me know if there is anything else that I am missing that you would like me to add to this post/add in a comment! Lastly, many thanks in advance to whoever can help! ------------- LOG FILE (latest.log) ------------- (from /Users/<NAME OF USER>/cursforge/minecraft/Instances/<THE NAME OF MY EMPTY MODPACK>/logs/latest.log) (This was made after running an empty modpack with same versions for all apps) ("[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/hxXvGGEK ------------- DEBUG.LOG (I realized that I should have put this here first after I had done all of the work on putting latest.log in) -------------------- (again, "[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/Fmh8GHYs
    • Pastebin... https://pastebin.com/Y3iZ85L5   Brand new profile, does not point to a mod as far as I can tell, my fatal message just has something about mixins. Don't know much about reading logs like this, but am genuinely stuck, please help. Java updated, pc restarted.
    • Fastfund recovery helps an individual to get back their scammed funds irrespective of nationality, Romance scam funds and Broker's scam, all kinds of scam funds are 100% accurately recovered without disappointment, their goal is to give all those who seek help to recover lost satisfaction of funds recovery within 72 hours After countless hours of research and desperate attempts to find a solution, I stumbled upon FASTFUND RECOVERY. It was like finding an oasis in the middle of a desert. Their website promised to help victims of scams reclaim what was rightfully theirs, and I instantly knew I had to give them a shot. Before diving headfirst into the recovery process, I wanted to make sure that FASTFUND RECOVERY was the real deal. So, I did my due diligence and looked into their expertise and reputation. To my relief, I found that they had an impeccable track record, successfully assisting countless individuals in recovering their lost funds. Their team consisted of experts in cybersecurity and financial fraud, armed with the knowledge and tools needed to tackle even the most intricate scams. With their reputation preceding them, I felt a renewed sense of hope. FASTFUND RECOVERY successfully came to my aid and got back the amount I lost to these scammers and for this, I am sending this article for clarification. The info of FASTFUND RECOVERY is email: Fastfundrecovery8 (@)Gmail (.) com. Web fastfundrecovery(.)com. (W/A 1 807/500/7554)
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.