Jump to content

Recommended Posts

Posted

Hi all,

 

    I have been working on making a simple mod that shears sheep when they collide with the block.  Everything works fine, except sometimes on loading, the first time the block shears the sheep I can't pick up the wool.  I think it has something to do with the server side not registering the items on the first collision but i am not sure.

 

    Another odd thing that happens,  usually right after loading, the game sometimes crashes when crafting the "Shear Block". 

 

Here is the code:

 

ShearBlockMod.java

 

package net.bb.shearblockmod;

import java.util.logging.LogManager;
import java.util.logging.Logger;

import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;

@Mod(modid = ShearBlockMod.modid, version = ShearBlockMod.version)
public class ShearBlockMod {
public static final String modid = "ShearBlockMod";
public static final String version = "0.1 MC1.7.2";

@EventHandler
    public void preinit(FMLPreInitializationEvent event)
    {
        GameRegistry.addRecipe(new ItemStack(ShearBlockMod.shearBlock), new Object[]{
            "  A",
            " A ",
            "A  ",
            'A', Items.iron_ingot});
        }




public static CreativeTabs tabExample = new CreativeTabs("tabExample") {
	public Item getTabIconItem() {
		return Items.bed;
	}
};

public static CreativeTabs tabExample2 = new CreativeTabs("tabExample2") {
	public Item getTabIconItem() {
		return Item.getItemFromBlock(Blocks.carpet);
	}
};





public static Item tutorialItem;

public static Block shearBlock;

@EventHandler
public void preInit(FMLPreInitializationEvent event) {
	shearBlock = new BlockShearBlock().setBlockName("shearBlock").setCreativeTab(tabExample2).setBlockTextureName(modid + ":" + "shearBlock");
	GameRegistry.registerBlock(shearBlock, "shearBlock");

	tutorialItem = new Item().setCreativeTab(tabExample).setUnlocalizedName("tutorialItem").setTextureName(modid + ":" + "tutorialItem");
	GameRegistry.registerItem(tutorialItem, "tutorialItem");
}

@EventHandler
public void init(FMLInitializationEvent event) {

}

@EventHandler
public void postInit(FMLPostInitializationEvent event) {

}
}

 

BlockShearBlock.java

 


package net.bb.shearblockmod;

import java.util.ArrayList;
import java.util.Random;

import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.common.IShearable;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockShearBlock extends Block{
boolean powered;

public BlockShearBlock(){

	super(Material.rock);
	this.setTickRandomly(true);




}	


public void onBlockAdded(World world, int x, int y, int z, Block id)	
{
	if (!world.isRemote)
        {
		//AxisAlignedBB myAABB = AxisAlignedBB.getBoundingBox(x+1, y+1, z+1, x-1, y+2, z-1);
		if (world.getBlockPowerInput(x, y, z) > 0)
        {
        	System.out.println("new power on!");
        	powered = true;
        }
		else
		{
			System.out.println("new power off!");
			powered = false;
		}


        }
	//world.notifyBlocksOfNeighborChange(x, y, z, this);
}



@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
	int shearBlockID = Block.getIdFromBlock(null); 
	if (!par1World.isRemote)
	System.out.println("Block Activated Test" + shearBlockID );
	return true;
}



public void shearSheep(World world, int x, int y, int z, Entity target)
{

		Entity theSheep = (Entity)target;
		if (target instanceof IShearable)
		{
			IShearable Entity = (IShearable)theSheep;
            if (Entity.isShearable(null, world , x, y, z))
            {
            	ArrayList<ItemStack> drops = ((IShearable) theSheep).onSheared(null, world, (int)target.posX, (int)target.posY, (int)target.posZ, 3);
            	Random rand = new Random();
                for(ItemStack stack : drops)
                {
                    EntityItem ent = ((Entity) Entity).entityDropItem(stack, 1.0F);
                    ent.motionY += rand.nextFloat() * 0.05F;
                    ent.motionX += (rand.nextFloat() - rand.nextFloat()) * 0.1F;
                    ent.motionZ += (rand.nextFloat() - rand.nextFloat()) * 0.1F;
                    
                }
            }
		}
	}





@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int i, int j, int k)
{
	float f = 0.0625F;
	return AxisAlignedBB.getBoundingBox((float)i + f, j, (float)k + f, (float)(i + 1) - f, (float)(j + 1) - f, (float)(k + 1) - f);
}

@Override
public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int i, int j, int k)
{
	float f = 0.0625F;
	return AxisAlignedBB.getBoundingBox((float)i + f, j, (float)k + f, (float)(i + 1) - f, j + 1, (float)(k + 1) - f);
}



@Override

public void onEntityCollidedWithBlock(World world, int i, int j, int k, Entity entity)
{
	//if(powered == true)
	{
	System.out.println("Engage Shearing!");
	shearSheep(world, (int)entity.posX, (int)entity.posY, (int)entity.posZ, entity);

	}
}
}


 

 

Any help would be much appreciated....

Posted

I might be wrong, but I don't think you can register recipes in the PreInit, I think they have to be done in the PostInit, as for the item thing, I don't know I am not to good with aabbs and things like that. Hope this helps!

Don't be afraid to ask question when modding, there are no stupid question! Unless you don't know java then all your questions are stupid!

Posted

You are spawning the Items on the client side, but you need to spawn them server side. You need to use

if(!world.isRemote) at the beginning of your shearSheep method.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Posted

Mecblader:

 

I had this same issue before I created the crafting recipe, so i don't think that is the problem

 

Edit:  I meant to say: I had the "items can't be picked up issue"  before I had the crafting recipe.  You might be on to something about the crash on crafting.  I will have to dig deeper on this.

 

larsgerrits:

 

I changed the shearSheep method to include if (!world.isRemote), but now it crashes every time I try to craft the item???

 

code here:

 


public void shearSheep(World world, int x, int y, int z, Entity target) {
	if (!world.isRemote) {
		Entity theSheep = (Entity) target;
		if (target instanceof IShearable) {
			IShearable Entity = (IShearable) theSheep;
			if (Entity.isShearable(null, world, x, y, z)) {
				ArrayList<ItemStack> drops = ((IShearable) theSheep)
						.onSheared(null, world, (int) target.posX,
								(int) target.posY, (int) target.posZ, 3);
				Random rand = new Random();
				for (ItemStack stack : drops) {
					EntityItem ent = ((Entity) Entity).entityDropItem(
							stack, 1.0F);
					ent.motionY += rand.nextFloat() * 0.05F;
					ent.motionX += (rand.nextFloat() - rand.nextFloat()) * 0.1F;
					ent.motionZ += (rand.nextFloat() - rand.nextFloat()) * 0.1F;

				}
			}
		} else {
		}
	}
}

 

Here is the message from the server:

 

 

java.lang.NullPointerException
        at net.minecraft.item.ItemStack.func_77980_a(ItemStack.java:385) ~[add.class:?]
        at net.minecraft.inventory.SlotCrafting.func_75208_c(SlotCrafting.java:53) ~[aax.class:?]
        at net.minecraft.inventory.SlotCrafting.func_82870_a(SlotCrafting.java:110) ~[aax.class:?]
        at net.minecraft.inventory.Container.func_75144_a(SourceFile:238) ~[zs.class:?]
        at net.minecraft.network.NetHandlerPlayServer.func_147351_a(NetHandlerPlayServer.java:878) ~[nh.class:?]
        at net.minecraft.network.play.client.C0EPacketClickWindow.func_148833_a(SourceFile:32) ~[ix.class:?]
        at net.minecraft.network.play.client.C0EPacketClickWindow.func_148833_a(SourceFile:10) ~[ix.class:?]
        at net.minecraft.network.NetworkManager.func_74428_b(NetworkManager.java:212) ~[ej.class:?]
        at net.minecraft.network.NetworkSystem.func_151269_c(NetworkSystem.java:165) [nc.class:?]
        at net.minecraft.server.MinecraftServer.func_71190_q(MinecraftServer.java:659) [MinecraftServer.class:?]
        at net.minecraft.server.dedicated.DedicatedServer.func_71190_q(DedicatedServer.java:335) [lt.class:?]
        at net.minecraft.server.MinecraftServer.func_71217_p(MinecraftServer.java:547) [MinecraftServer.class:?]
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:427) [MinecraftServer.class:?]
        at net.minecraft.server.MinecraftServer$2.run(MinecraftServer.java:685) [li.class:?]

 

Posted

Why do you have 2 FMLPreInitializationEvents? Copy the recipe to the FMLInitializationEvent and remove the first FMLPreInitializationEvent. That should solve the issue, as the issue was caused by registering a recipe with a ItemStack containing a null item (as the items weren't initialized before the recipe).

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Posted

Thank you!  :)

 

I didn't intend to have 2 preInitializationEvents, I copied the recipe portion from another mod I was working on and accidentally grabbed that part.  That makes sense that the item should be registered before the recipe. 

 

It looks like the if (!world.isRemote) fixed the item issue also.

 

Thank you very much!

 

 

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.