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

    • OLXTOTO: Menikmati Sensasi Bermain Togel dan Slot dengan Aman dan Mengasyikkan   Dunia perjudian daring terus berkembang dengan cepat, dan salah satu situs yang telah menonjol dalam pasar adalah OLXTOTO. Sebagai platform resmi untuk permainan togel dan slot, OLXTOTO telah memenangkan kepercayaan banyak pemain dengan menyediakan pengalaman bermain yang aman, adil, dan mengasyikkan.   Keamanan Sebagai Prioritas Utama   Salah satu aspek utama yang membuat OLXTOTO begitu menonjol adalah komitmennya terhadap keamanan pemain. Dengan menggunakan teknologi enkripsi terkini, situs ini memastikan bahwa semua informasi pribadi dan keuangan para pemain tetap aman dan terlindungi dari akses yang tidak sah.   Beragam Permainan yang Menarik   Di OLXTOTO, pemain dapat menemukan beragam permainan yang menarik untuk dinikmati. Mulai dari permainan klasik seperti togel hingga slot modern dengan fitur-fitur inovatif, ada sesuatu untuk setiap selera dan preferensi. Grafik yang memukau dan efek suara yang mengagumkan menambah keseruan setiap putaran. Peluang Menang yang Tinggi   Salah satu hal yang paling menarik bagi para pemain adalah peluang menang yang tinggi yang ditawarkan oleh OLXTOTO. Dengan pembayaran yang adil dan peluang yang setara bagi semua pemain, setiap taruhan memberikan kesempatan nyata untuk memenangkan hadiah besar.   Layanan Pelanggan yang Responsif   Tim layanan pelanggan OLXTOTO siap membantu para pemain dengan setiap pertanyaan atau masalah yang mereka hadapi. Dengan layanan yang ramah dan responsif, pemain dapat yakin bahwa mereka akan mendapatkan bantuan yang mereka butuhkan dengan cepat dan efisien.   Kesimpulan   OLXTOTO telah membuktikan dirinya sebagai salah satu situs terbaik untuk penggemar togel dan slot online. Dengan fokus pada keamanan, beragam permainan yang menarik, peluang menang yang tinggi, dan layanan pelanggan yang luar biasa, tidak mengherankan bahwa situs ini telah menjadi pilihan utama bagi banyak pemain.   Jadi, jika Anda mencari pengalaman bermain yang aman, adil, dan mengasyikkan, jangan ragu untuk bergabung dengan OLXTOTO hari ini dan rasakan sensasi kemenangan!      
    • i notice a change if i add the min and max ram in the line like this for example:    # Xmx and Xms set the maximum and minimum RAM usage, respectively. # They can take any number, followed by an M or a G. # M means Megabyte, G means Gigabyte. # For example, to set the maximum to 3GB: -Xmx3G # To set the minimum to 2.5GB: -Xms2500M # A good default for a modded server is 4GB. # Uncomment the next line to set it. -Xmx10240M -Xms8192M    i need to make more experiments but for now this apparently works.
    • Selamat datang di OLXTOTO, situs slot gacor terpanas yang sedang booming di industri perjudian online. Jika Anda mencari pengalaman bermain yang luar biasa, maka OLXTOTO adalah tempat yang tepat untuk Anda. Dapatkan sensasi tidak biasa dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering. Di sini, Anda akan merasakan keseruan yang luar biasa dalam bermain judi slot. DAFTAR OLXTOTO DISINI LOGIN OLXTOTO DISINI AKUN PRO OLXTOTO DISINI   Slot Gacor untuk Sensasi Bermain Maksimal Olahraga cepat dan seru dengan slot gacor di OLXTOTO. Rasakan sensasi bermain maksimal dengan mesin slot yang memberikan kemenangan beruntun. Temukan keberuntungan Anda di antara berbagai pilihan slot gacor yang tersedia dan rasakan kegembiraan bermain judi slot yang tak terlupakan. Situs Slot Terpercaya dengan Pilihan Terlengkap OLXTOTO adalah situs slot terpercaya yang menawarkan pilihan terlengkap dalam perjudian online. Nikmati berbagai genre dan tema slot online yang menarik, dari slot klasik hingga slot video yang inovatif. Dipercaya oleh jutaan pemain, OLXTOTO memberikan pengalaman bermain yang aman dan terjamin.   Jackpot Slot Maxwin Sering Untuk Peluang Besar Di OLXTOTO, kami tidak hanya memberikan hadiah slot biasa, tapi juga memberikan kesempatan kepada pemain untuk memenangkan jackpot slot maxwin yang sering. Dengan demikian, Anda dapat meraih keberuntungan besar dan memenangkan ribuan rupiah sebagai hadiah jackpot slot maxwin kami. Jackpot slot maxwin merupakan peluang besar bagi para pemain judi slot untuk meraih keuntungan yang lebih besar. Dalam permainan kami, Anda tidak harus terpaku pada kemenangan biasa saja. Kami hadir dengan jackpot slot maxwin yang sering, sehingga Anda memiliki peluang yang lebih besar untuk meraih kemenangan besar dengan hadiah yang menggiurkan. Dalam permainan judi slot, pengalaman bermain bukan hanya tentang keseruan dan hiburan semata. Kami memahami bahwa para pemain juga menginginkan kesempatan untuk meraih keberuntungan besar. Oleh karena itu, OLXTOTO hadir dengan jackpot slot maxwin yang sering untuk memberikan peluang besar kepada para pemain kami. Peluang Besar Menang Jackpot Slot Maxwin Peluang menang jackpot slot maxwin di OLXTOTO sangatlah besar. Anda tidak perlu khawatir tentang batasan atau pembatasan dalam meraih jackpot tersebut. Kami ingin memberikan kesempatan kepada semua pemain kami untuk merasakan sensasi menang dalam jumlah yang luar biasa. Jackpot slot maxwin kami dibuka untuk semua pemain judi slot di OLXTOTO. Anda memiliki peluang yang sama dengan pemain lainnya untuk memenangkan hadiah jackpot yang besar. Kami percaya bahwa semua orang memiliki kesempatan untuk meraih keberuntungan besar, dan itulah mengapa kami menyediakan jackpot slot maxwin yang sering untuk memenuhi harapan dan keinginan Anda.  
    • LOGIN DAN DAFTAR DISINI SEKARANG !!!! Blacktogel adalah situs judi slot online yang menjadi pilihan banyak penggemar judi slot gacor di Indonesia. Dengan platform yang sangat user-friendly dan berbagai macam permainan slot yang tersedia, Blacktogel menjadi tempat yang tepat untuk penggemar judi slot online. Dalam artikel ini, kami akan membahas tentang Blacktogel dan keunggulan situs slot gacor online yang disediakan.  
    • Situs bandar slot online Gacor dengan bonus terbesar saat ini sedang menjadi sorotan para pemain judi online. Dengan persaingan yang semakin ketat dalam industri perjudian online, pemain mencari situs yang tidak hanya menawarkan permainan slot yang gacor (sering memberikan kemenangan), tetapi juga bonus terbesar yang bisa meningkatkan peluang menang. Daftar disini : https://gesit.io/googlegopek
  • Topics

×
×
  • Create New...

Important Information

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