Jump to content

Perform code on Item right click


Kekz

Recommended Posts

I'm new to Minecraft modding but have experience in Java.  

I used some tutorials in order to add an item, so now I want to give this item a purpose.  

There are 2 main things I'm trying to solve:  

  1. If the player right clicks on the ground while holding my item, I need to save the coordinates, in order to spawn blocks at that location
  2. I somehow need to write commands in the in game chat to spawn the blocks, I was thinking something like "/setblock <COORDINATES_FROM_RIGHT_CLICK> <BLOCK_TYPE>. (maybe there is a better way?)

 I probably need some kind of EventHandler for both, but I have no idea where to start.  

Maybe someone can give me some tips and help me go in the right direction, I would be very thankful.  

In the following I will post the code I have so far.  

 

Main mod class:

Spoiler

package com.opkekz.imagespawner;

import com.opkekz.imagespawner.configuration.ConfigurationHandler;
import com.opkekz.imagespawner.init.ModItems;
import com.opkekz.imagespawner.item.ImageSpawnerItem;
import com.opkekz.imagespawner.proxy.IProxy;
import com.opkekz.imagespawner.reference.Reference;

import net.minecraft.item.Item;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION)
public class ImageSpawner {
    
    @Mod.Instance(Reference.MOD_ID)
    public static ImageSpawner instance;
    
    @SidedProxy(clientSide=Reference.CLIENT_PROXY, serverSide=Reference.SERVER_PROXY)
    public static IProxy proxy;

    @Mod.EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        ConfigurationHandler.init(event.getSuggestedConfigurationFile());
        ModItems.init();
        
    }
    
    @Mod.EventHandler
    public void init(FMLInitializationEvent event) {
        proxy.init();
    }
    
    @Mod.EventHandler
    public void postInit(FMLPostInitializationEvent event) {
        
    }
    
}

 

Reference class:  

Spoiler

package com.opkekz.imagespawner.reference;

public class Reference {
    
    public static final String MOD_ID = "imagespawner";
    public static final String MOD_NAME = "ImageSpawner";
    public static final String VERSION = "1.12.2-1.0";
    public static final String CLIENT_PROXY = "com.opkekz.imagespawner.proxy.ClientProxy";
    public static final String SERVER_PROXY = "com.opkekz.imagespawner.proxy.ServerProxy";
    
    public static enum ImageSpawnerEnum {
        IMAGESPAWNER("spawner", "imagespawner");
        
        private String unlocalizedName;
        private String registryName;
        
        ImageSpawnerEnum(String unlocalizedName, String registryName) {
            this.unlocalizedName = unlocalizedName;
            this.registryName = registryName;
        }
        
        public String getRegistryName() {
            return registryName;
        }
        
        public String getUnlocalizedName() {
            return unlocalizedName;
        }
    }

}

 

ModItems class:  

Spoiler

package com.opkekz.imagespawner.init;

import java.util.HashSet;
import java.util.Set;

import com.opkekz.imagespawner.item.ImageSpawnerItem;
import com.opkekz.imagespawner.reference.Reference;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;

@Mod.EventBusSubscriber(modid=Reference.MOD_ID)
public class ModItems {
    
    public static final ImageSpawnerItem spawner = new ImageSpawnerItem();
    
    public static void init() {
        
        //spawner.setRegistryName("imageSpawner");
        ForgeRegistries.ITEMS.register(spawner);
        
    }
    
    public static void registerRenders() {
        registerRender(spawner);
    }
    
    public static void registerRender(Item item) {
        Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));  // I read on this forum that this is not the ideal approach, but it's working for me
    }
    
}

 

Item class:  

Spoiler

package com.opkekz.imagespawner.item;

import com.google.common.eventbus.Subscribe;
import com.opkekz.imagespawner.reference.Reference;

import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.client.CPacketChatMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ImageSpawnerItem extends Item{
    
    public ImageSpawnerItem() {
        
        super();
        this.setCreativeTab(CreativeTabs.TOOLS);
        setUnlocalizedName(Reference.ImageSpawnerEnum.IMAGESPAWNER.getUnlocalizedName());
        setRegistryName(Reference.ImageSpawnerEnum.IMAGESPAWNER.getRegistryName());
        
    }
    
    
    @Override
    public String getUnlocalizedName() {
        
        return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
        
    }
    
    @Override
    public String getUnlocalizedName(ItemStack itemStack) {
        return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
    }
    
    protected String getUnwrappedUnlocalizedName(String unlocalizedName) {
        return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
    }

}

 If there are more information I can give, please let me know.

Link to comment
Share on other sites

6 minutes ago, diesieben07 said:
  • It is not "not ideal", it is fundamentally broken and causes problems. Your way of doing it will additionally completely crash a dedicated server.
  • Your code does not even contain any kind of attempt at the problems you are describing. What have you tried?

I don't plan on releasing the mod, it's just a project I'm doing and I wanted to try to implement it in Minecraft.  

 

I tried some methods that I found on other posts with similar questions, but none worked:  

For example:

@Subscribe
	public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
	{
		String command = "Hello, Test!";
		Minecraft.getMinecraft().getConnection().sendPacket((new CPacketChatMessage("/help")));
		return par1ItemStack;
	}

I couldn't figure out how to use the "@Subscribe" annotation properly

Edited by Kekz
Link to comment
Share on other sites

4 minutes ago, diesieben07 said:

I am not even sure what that code is supposed to achieve.

  • Item#onItemUse will be called when your item is used (right-clicked) on a block.
  • "Spawning" blocks can be done via World#setBlockState on the server. There is no need to send packets or chat messages.

Thanks, I will look into those methods.  

For clarification: I wrote some code that takes an image and transforms each pixel into a String, like "yellow".  

I thought I could make a mod out of this, where you can instantly spawn an image. (May already exist)

Edited by Kekz
Link to comment
Share on other sites

7 minutes ago, Kekz said:

For clarification: I wrote some code that takes an image and transforms each pixel into a String, like "yellow".  

I thought I could make a mod out of this, where you can instantly spawn an image. (May already exist)

Sorry, but your clarification is slightly ambiguous.

What do you mean by "spawn an image"?

Edited by DavidM

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Link to comment
Share on other sites

1 minute ago, DavidM said:

Sorry, but your clarification is slightly ambiguous.

What do you mean by "spawn an image"?

Each pixel of the image will be mapped to a String, in this case a Minecraftblock. Then these blocks will be spawned in order to create the image.

Link to comment
Share on other sites

12 minutes ago, Kekz said:

Each pixel of the image will be mapped to a String, in this case a Minecraftblock. Then these blocks will be spawned in order to create the image.

In this case you should just map each color to a block; there is no need for strings.

Something like Map<Color, Block> should suffice.

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Link to comment
Share on other sites

1 minute ago, DavidM said:

In this case you should just map each color to a block; there is no need for strings.

Something like Map<Color, Block> should suffice.

Thanks, but that's not the part of the mod I'm having issues with ^^

Link to comment
Share on other sites

36 minutes ago, diesieben07 said:

Item#onItemUse will be called when your item is used (right-clicked) on a block.

Is there an event for that? I tried the example from the Forge Doc with the EntityItemPickUpEvent, and that works.  

Couldn't find any Events that are called on Item use.

At least now I have somewhere to start.

Link to comment
Share on other sites

The player interact event has a few subclasses that do what you want.

 

Also: http://wiki.c2.com/?StringlyTyped

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

45 minutes ago, Kekz said:

Thanks, but that's not the part of the mod I'm having issues with ^^

I thought your main problem was fixed...

If you want to implement the behavior on a custom item, just override Item#onItemUse.

  • Thanks 1

Some tips:

Spoiler

Modder Support:

Spoiler

1. Do not follow tutorials on YouTube, especially TechnoVision (previously called Loremaster) and HarryTalks, due to their promotion of bad practice and usage of outdated code.

2. Always post your code.

3. Never copy and paste code. You won't learn anything from doing that.

4. 

Quote

Programming via Eclipse's hotfixes will get you nowhere

5. Learn to use your IDE, especially the debugger.

6.

Quote

The "picture that's worth 1000 words" only works if there's an obvious problem or a freehand red circle around it.

Support & Bug Reports:

Spoiler

1. Read the EAQ before asking for help. Remember to provide the appropriate log(s).

2. Versions below 1.11 are no longer supported due to their age. Update to a modern version of Minecraft to receive support.

 

 

Link to comment
Share on other sites

Is there a way to spawn colored wool with 

worldIn.setBlockState(pos, state);

I use 

Blocks.CLAY.getDefaultState();

to spawn a clay block, but I can only find  

Blocks.WOOL;

with no option for colored wool.

Link to comment
Share on other sites

I don't know exactly what you need to do but I think it needs to be something along the lines of

Blocks.WOOL.getDefaultState().withProperty();

Thing is I have not messed with wool so I don't know what properties it has or what you need to put inside the withProperty() part

  • Thanks 1
Link to comment
Share on other sites

On 4/26/2019 at 7:21 PM, Blue_Atlas said:

I don't know exactly what you need to do but I think it needs to be something along the lines of


Blocks.WOOL.getDefaultState().withProperty();

Thing is I have not messed with wool so I don't know what properties it has or what you need to put inside the withProperty() part

Figured it out btw:  

Create a PropertyEnum constant for the EnumDyeColor "COLOR":

public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.<EnumDyeColor>create("color", EnumDyeColor.class);

Select a color for wool (should also work for clay):  

Blocks.WOOL.getDefaultState().withProperty(COLOR, EnumDyeColor.WHITE);

 

Link to comment
Share on other sites

4 hours ago, Kekz said:

Create a PropertyEnum constant for the EnumDyeColor "COLOR":


public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.<EnumDyeColor>create("color", EnumDyeColor.class);

Select a color for wool (should also work for clay):  


Blocks.WOOL.getDefaultState().withProperty(COLOR, EnumDyeColor.WHITE);

 

No. Use BlockWool.COLOR or whatever it’s called

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

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

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

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