Jump to content

Recommended Posts

Posted

project on github for referencing: https://github.com/InterdimensionalCat/ModTest/tree/master/java/com/benthom123/test

 

I am trying to program guns in minecraft. So far I have everything working except for one thing. I have a abstract class ItemGun as a template, and ItemAmmo for an ammo template. The idea is that when "reloading" the gun it uses up one of the specified ammo type. However, whenever I remove the item stack from the player inventory, the texture will disappear until something else updates the inventory, then reappears in the same quantity. I assume the game has some sort of failsafe checking, but I am unaware of what it might be.

 

I looked in the ItemBucket class of minecraft's source code and got no answers there.

 

Here is the class ItemGun:

package com.benthom123.test.items;

import com.benthom123.test.ModItems;
import com.benthom123.test.modClass;

import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import com.benthom123.test.items.ItemAmmo;

public abstract class ItemGun extends Item {

	protected int clipSize;
	protected int currentClip;
	protected int maxDamage;
	protected boolean reloading;
	protected ItemStack ammo;
	protected final int fireRate;
	protected int fireCD;
	
	public ItemGun(String name, int clipSize, int reloadTime, ItemAmmo ammo, int fireRate) {
		setRegistryName(name);
        setUnlocalizedName(modClass.MODID + "." + name);
        this.setCreativeTab(ModItems.powerCrystal);
        this.currentClip = 0;
        this.clipSize = clipSize;
        
        this.setMaxDamage(reloadTime + 1);
		maxDamage = reloadTime;
		this.isDamageable();
		this.setMaxStackSize(1);
		
		this.ammo = new ItemStack(ammo, 1, 0);
		this.fireRate = fireRate;
		fireCD = 0;
    }
	
    public abstract void shoot(World worldIn, EntityPlayer playerIn, EnumHand handIn);
	
    @SideOnly(Side.CLIENT)
    public void initModel() {
       ModelLoader.setCustomModelResourceLocation(this, 0, new ModelResourceLocation(getRegistryName(), "inventory"));
	}
	
    
    /**
     * Called when the equipped item is right clicked.
     */
    
    public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) {
    	ItemStack itemstack = playerIn.getHeldItem(handIn);
    	if (!reloading&&fireCD == 0) {
			if(currentClip > 0) {
				shoot(worldIn, playerIn, handIn);
				if(!worldIn.isRemote) {
					currentClip--;
					System.out.println(currentClip);
					fireCD = fireRate;
				}
				playerIn.addStat(StatList.getObjectUseStats(this));
				//itemstack.setItemDamage(itemstack.getItemDamage() - (maxDamage*(clipSize - currentClip) / clipSize));
				itemstack.damageItem(maxDamage / clipSize, playerIn);
				System.out.println(itemstack.getItemDamage());
				return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, itemstack);
			} else {
				if(playerIn.inventory.hasItemStack(new ItemStack(ModItems.tttremington))) {
					reloading = true;
					//itemstack.setItemDamage(maxDamage);
					currentClip = clipSize;
						//playerIn.inventory.getStackInSlot(playerIn.inventory.getSlotFor(new ItemStack(ammo, 1))).shrink(1);
						for (int i = 0; i < playerIn.inventory.getSizeInventory(); i++) {
							if (playerIn.inventory.getStackInSlot(i).isItemEqual(new ItemStack(ModItems.tttremington))) {
								//ItemAmmo.remove(i, playerIn);
								//playerIn.inventory.deleteStack(playerIn.inventory.getStackInSlot(i));
								//playerIn.inventory.getStackInSlot(i).damageItem(1, playerIn);
								///playerIn.inventory.setInventorySlotContents(i, playerIn.inventory.getStackInSlot(i));
								ItemStack is = playerIn.inventory.getStackInSlot(i);
			                    if (!playerIn.capabilities.isCreativeMode)
			                    {
			                    	is.shrink(1);

			                        if (is.isEmpty())
			                        {
			                        	playerIn.inventory.deleteStack(is);
			                        }
			                    }

								break;
							}
						} 
	               playerIn.addStat(StatList.getObjectUseStats(this));
				}
			}
		}
    	
    	 return new ActionResult<ItemStack>(EnumActionResult.FAIL, itemstack);
    }
    
	@Override
	public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
		if (reloading) {
			if (stack.getItemDamage() > 0) {
				stack.setItemDamage(stack.getItemDamage() - 1);
				System.out.println(stack.getItemDamage());
			} else {
				reloading = false;
			}
		}
		
		if(fireCD > 0) {
			fireCD--;
		}
    }
}

 

 

and here is class itemammo:

 

package com.benthom123.test.items;

import com.benthom123.test.ModItems;
import com.benthom123.test.modClass;

import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ItemAmmo extends Item {
	
	
	public boolean used = false;
	

	public ItemAmmo(String name, int stackSize) {
		setRegistryName(name);
        setUnlocalizedName(modClass.MODID + "." + name);
        this.setCreativeTab(ModItems.powerCrystal);
        this.setMaxStackSize(1);
        this.setMaxDamage(1);
	}
	
	@SideOnly(Side.CLIENT)
    public void initModel() {
       ModelLoader.setCustomModelResourceLocation(this, 0, new ModelResourceLocation(getRegistryName(), "inventory"));
	}
	
	public static void remove(int i, EntityPlayer playerIn) { //this is currently unused, ignore it
		//ItemStack ii = playerIn.inventory.removeStackFromSlot(i);
		playerIn.inventory.deleteStack(playerIn.inventory.getStackInSlot(i));
		//playerIn.replaceItemInInventory(i, new ItemStack(Items.IRON_NUGGET, 1, 0));
		//ii = null;
	}
}

 

Posted (edited)

look at how ItemBow does it

noticed that your already trying to do it the same way

can you post a GitHub? your ItemGun class is rather hard to read

Ignore this post

 

Edited by Cadiboo

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)

Posted (edited)
public abstract class ItemGun extends Item

why abstract?

 

public abstract void shoot(World worldIn, EntityPlayer playerIn, EnumHand handIn);

 

why is it abstract and why doesn't it do anything?

Edited by Cadiboo

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)

Posted (edited)

github link is on the top of the post but here it is: https://github.com/InterdimensionalCat/ModTest/tree/master/java/com/benthom123/test

 

EDIT: the class is abstract because I am using it as a template for multiple guns (eventually), the only current subclass is ArmaLite15, i can post the code for that here however it does not touch the itemstack at all.

 

Edited by InterdimensionalCat
Posted
5 minutes ago, Cadiboo said:

public abstract class ItemGun extends Item

why abstract?

 

public abstract void shoot(World worldIn, EntityPlayer playerIn, EnumHand handIn);

 

why is it abstract and why doesn't it do anything?

 

as I said I'm using it as a template for different types of guns, the current sublcass I am testing it on is here :

 

package com.benthom123.test.items;

import com.benthom123.test.ModItems;
import com.benthom123.test.entity.EntitySmokeShot;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;

public class ArmaLite15 extends ItemGun {

	public boolean firstTick = true;
	
	public ArmaLite15(String name) {
		super(name, 25, 100, ModItems.tttremington, 1);
		
	}

	@Override
	public void shoot(World worldIn, EntityPlayer playerIn, EnumHand handIn) {		
		if (!worldIn.isRemote) {
			
			EntitySmokeShot entitysmokeshot = new EntitySmokeShot(worldIn, playerIn);
			entitysmokeshot.shoot(playerIn, playerIn.rotationPitch, playerIn.rotationYaw, 0.0F, 1.5F, 10.0F);
			worldIn.spawnEntity(entitysmokeshot);
			worldIn.playSound((EntityPlayer) null, playerIn.posX, playerIn.posY, playerIn.posZ, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.NEUTRAL, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
		}
		
		playerIn.rotationYaw += this.itemRand.nextGaussian()*1.5/**Math.signum(this.itemRand.nextDouble() - 0.5)*/;
		playerIn.rotationPitch -= Math.abs(this.itemRand.nextGaussian()*3.0);
	}

	@Override
	public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
		if(firstTick) {
			ammo = new ItemStack(ModItems.tttremington, 1, 0);
			firstTick = false;
		}
		
		super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
	}
	
}

 

this overrides the abstract method shoot(), again, this should not have any effect on the current problem as far as i can tell.

Posted

what is fireCD

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)

Posted

itemstack.damageItem(maxDamage / clipSize, playerIn);

 

what are you trying to do here??

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)

Posted

You're on 1.12. You don't need to "delete" stacks. A stack with 0 size is already the same as air.

 

If "the inventory updates and the item comes back" thing is happening, that sounds to me like you're only subtracting 1 from the stack size on the client and not doing it on the server. So when "the inventory updates" (cough, gets an update packet from the server) the item "reappears" again because it was never gone in the first place.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
Just now, Draco18s said:

You're on 1.12. You don't need to "delete" stacks. A stack with 0 size is already the same as air.

 

If "the inventory updates and the item comes back" thing is happening, that sounds to me like you're only subtracting 1 from the stack size on the client and not doing it on the server. So when "the inventory updates" (cough, gets an update packet from the server) the item "reappears" again because it was never gone in the first place.

 

Thank you for your help, I am unfamiliar with how to handle server packets, can you please elaborate on how to deal with them?

Posted

You don't need to do anything except reduce the stack size on the server.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

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

    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
    • All versions of Minecraft Forge suddenly black screen even without mods (tried reinstalling original Minecraft, Java, updating drivers doesn't work)
  • Topics

×
×
  • Create New...

Important Information

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