Jump to content

Recommended Posts

Posted

In my mod I have some blocks that are ver similar, and so they use the same class. The problem is that when I place the blocks from the same class next to each other they all start to use the texture and particle effects of the most recently placed one.

package com.leo.mobsuppressors.blocks;

import com.leo.mobsuppressors.CreativeTab;
import com.leo.mobsuppressors.MobSuppressors;
import com.leo.mobsuppressors.gui.ModGUIHandler;
import com.leo.mobsuppressors.tileentity.IMobSuppressorTE;
import com.leo.mobsuppressors.tileentity.TileEntityMobSuppressor;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

public class BlockMobSuppressor extends Block implements ITileEntityProvider {
	public static final PropertyBool is_powered = PropertyBool.create("is_powered");
	
	public static String type;
	
	protected BlockMobSuppressor(String unlocalizedName, String registryName, String type) {
		super(Material.IRON);
		this.setCreativeTab(CreativeTab.mobSuppressorCreativeTab);
		
		this.setUnlocalizedName(unlocalizedName);
		this.setRegistryName(registryName);
		
		this.setHardness(2);
		this.setResistance(6000f);
		this.setHarvestLevel("pickaxe", 3);
		
		this.setDefaultState(this.blockState.getBaseState().withProperty(is_powered, false));
		
		this.type = type;
	}
	
	@Override
	protected BlockStateContainer createBlockState() {
		return new BlockStateContainer(this, is_powered);
	}
	
	@Override
	public IBlockState getStateFromMeta(int meta) {
		return this.getDefaultState().withProperty(is_powered, meta == 0);
	}
	
	@Override
	public int getMetaFromState(IBlockState state) {
		return state.getValue(is_powered) ? 1: 0;
	}
	
	@Override
	public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
		return state.withProperty(is_powered, state.getValue(is_powered));
	}
	
	@Override
	public TileEntity createNewTileEntity(World worldIn, int meta) {
		return new TileEntityMobSuppressor(this, type);
	}
	
	@Override
	public void breakBlock(World world, BlockPos pos, IBlockState state) {
		super.breakBlock(world, pos, state);
		world.removeTileEntity(pos);
	}

	@Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
		if (!worldIn.isRemote) {
			playerIn.openGui(MobSuppressors.instance, ModGUIHandler.enderSuppressorGUIID, worldIn, pos.getX(), pos.getY(), pos.getZ());
		}
		
		return true;
	}	
}
package com.leo.mobsuppressors.blocks;

import java.util.ArrayList;

import com.leo.mobsuppressors.MobSuppressors;

import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class ModBlocks {
	public static Block enderSuppressor;
	public static Block creeperSuppressor;
	
	public static void createBlocks() {
		enderSuppressor = new BlockMobSuppressor("endersuppressor", "endersuppressor", "ender");
		creeperSuppressor = new BlockMobSuppressor("creepersuppressor", "creepersuppressor", "creeper");
	}
	
	public static void init() {
		createBlocks();
		GameRegistry.register(enderSuppressor);
		GameRegistry.register(new ItemBlock(enderSuppressor).setRegistryName("endersuppressor"));
		
		GameRegistry.register(creeperSuppressor);
		GameRegistry.register(new ItemBlock(creeperSuppressor).setRegistryName("creepersuppressor"));
	}
	
	public static void registerRenderers() {
		registerRenderer(enderSuppressor);
		registerRenderer(creeperSuppressor);
	}
	
	public static void registerRenderer(Block block) {
		Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), 0, new ModelResourceLocation(MobSuppressors.modid + ":" + block.getUnlocalizedName().substring(5), "inventory"));
	}
}

 

Posted
7 minutes ago, meee39 said:

public static String type;

You're defining the type in a static field. This means the value is the same globally, not different for different instances.

Posted
1 hour ago, Jay Avery said:

You're defining the type in a static field. This means the value is the same globally, not different for different instances.

Oops. I'm very silly. There is another problem with it though. When the fuel is consumed setFullPowerTicks makes the power set to 300 for one tick.

Posted
package com.leo.mobsuppressors.tileentity;

import java.util.Random;

import com.leo.mobsuppressors.blocks.BlockMobSuppressor;

import jline.internal.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ITickable;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class TileEntityMobSuppressor extends TileEntity implements ITickable, IMobSuppressorTE {
	public static BlockMobSuppressor block;
	public boolean isPublic;
	public static final int maxTicks = 300;
	public int powerTicksLeft = 0;
	public Random RNG = new Random();
	
	public String type;
	
	public ItemStackHandler itemStackHandler = new ItemStackHandler(1) {
		@Override
		protected void onContentsChanged(int slot) {
			markDirty();
		}
	};
	
	public TileEntityMobSuppressor() {}
	
	public TileEntityMobSuppressor(BlockMobSuppressor block, String type) {
		this.block = block;
		this.isPublic = true;
		this.type = type;
	}
	
	@Override
	public void update() {
		if (!(world.getBlockState(getPos()).getBlock() instanceof BlockMobSuppressor)) {
			return;
		}
	
		EnumParticleTypes particleType = EnumParticleTypes.CRIT;
		
		switch (type) {
		case "ender":
			particleType = EnumParticleTypes.PORTAL;
		case "creeper":
			particleType = EnumParticleTypes.EXPLOSION_NORMAL;
		}
		
		world.spawnParticle(particleType, RNG.nextFloat() + pos.getX(), RNG.nextFloat() + pos.getY(), RNG.nextFloat() + pos.getZ(), 0.1, 0.1, 0.1, 0);
		
		if (!world.isRemote) {
			updateInventory();
		}
	}
	
	private void updateInventory() {
		if (powerTicksLeft > 0) {
			powerTicksLeft--;
		} else {
			if (itemStackHandler.getStackInSlot(0).getCount() > 0) {
				itemStackHandler.getStackInSlot(0).shrink(1);
				setToFullPowerTicks();
			}
		}
		
		System.out.println(powerTicksLeft);
		
		world.markBlockRangeForRenderUpdate(pos, pos);
		world.setBlockState(getPos(), block.getDefaultState().withProperty(block.is_powered, powerTicksLeft > 0));
		
		markDirty();
	}
	
	public void sendUpdate(boolean powered) {
		if (!world.isRemote) {
			world.setBlockState(getPos(), world.getBlockState(getPos()).withProperty(block.is_powered, powered));
			world.markBlockRangeForRenderUpdate(pos, pos);
			world.notifyBlockUpdate(pos, world.getBlockState(getPos()), world.getBlockState(getPos()).withProperty(block.is_powered, powered), 3);
			world.scheduleBlockUpdate(pos,this.getBlockType(),0,0);
			markDirty();
		}
	}
	
	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound) {
		super.writeToNBT(compound);
		
		compound.setTag("items", itemStackHandler.serializeNBT());
		
		compound.setBoolean("isPublic", isPublic);
		compound.setInteger("powerTicksLeft", powerTicksLeft);
		
		return compound;
	}
	
	@Override
	public void readFromNBT(NBTTagCompound compound) {
		super.readFromNBT(compound);
		
		if (compound.hasKey("items")) {
			itemStackHandler.deserializeNBT((NBTTagCompound)compound.getTag("items"));
		}
		
		isPublic = compound.getBoolean("isPublic");
		powerTicksLeft = compound.getInteger("powerTicksLeft");
	}

	@Override
	@Nullable
	public SPacketUpdateTileEntity getUpdatePacket() {
		return new SPacketUpdateTileEntity(this.pos, 3, this.getUpdateTag());
	}

	@Override
	public NBTTagCompound getUpdateTag() {
		return this.writeToNBT(new NBTTagCompound());
	}
	
	@Override
	public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
		super.onDataPacket(net, pkt);
		handleUpdateTag(pkt.getNbtCompound());
	}
	
	@Override
	public boolean isPublic() {
		return isPublic;
	}

	@Override
	public void setToFullPowerTicks() {
		this.powerTicksLeft = maxTicks;
	}

	@Override
	public int getPowerTicksLeft() {
		return powerTicksLeft;
	}
	
	@Override
    public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
        if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return true;
        }
        return super.hasCapability(capability, facing);
    }

    @Override
    public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
        if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
            return (T) itemStackHandler;
        }
        return super.getCapability(capability, facing);
    }
	
	public boolean canInteractWith(EntityPlayer playerIn) {
        return !isInvalid() && playerIn.getDistanceSq(pos.add(0.5D, 0.5D, 0.5D)) <= 64D;
    }
}

 

Posted (edited)

What tells you that the power is reset after one tick? Are the values different on the server and client?

 

Edit: Actually this is probably because TEs are refreshed when the block state changes, which you do in your updateInventory method. To stop this from happening, you can override shouldRefresh in you TE to only return true if the block is different.

 

Also, your getActualState method does nothing, it just sets the powered property to... the current value of the powered property. If you have a TE to store the power information of the block, it's best not to store that information in the block's state as well - that just leaves more likelihood of them becoming mismatched somehow. Instead you can simplify it by only setting the block's powered property in getActualState, by checking the TE's data. Then scrap the metadata methods (because the powered property doesn't need to be stored in the block as it's already stored in the TE), and the setBlockStates in the TE (because it's all calculated in getActualState whenever it's needed).

 

On an unrelated note, your blocks are 'stringly typed'. You should use an enum for this purpose.

Edited by Jay Avery
  • Like 1
Posted
On 6/18/2017 at 5:26 AM, Jay Avery said:

You're defining the type in a static field.

While "type" shouldn't be static, it probably should be final.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

I have made every change you suggested (except for the type enum) although the blocks still seem to be turning into each other. I also installed WAILA to see if it was a graphical error or if the blocks were actually changing type; and they were.

Posted

Well, let's look at your tileentity class then shall we? It is common and also shared by both blocks.

In it's update method we see this:

3 hours ago, meee39 said:

world.setBlockState(getPos(), block.getDefaultState().withProperty(block.is_powered, powerTicksLeft > 0));

Oh, I wonder where is the block field at?

3 hours ago, meee39 said:

public static BlockMobSuppressor block;

And it is static. :P

 

Every time you place a new TileEntity you refresh this field for all your tileentities as it is static. The next tick all tileentities convert the blocks that they are bound to to the block that this field stores which conviniently is the block you've last placed.

 

Also it is probably not a good idea to call this

3 hours ago, meee39 said:

world.markBlockRangeForRenderUpdate(pos, pos);

each tick. Granted you are calling this on a server which does nothing by the way, but if you would call this on the client you would cause a lot of lag by the renderer having to redraw your block every tick.

  • Like 1
Posted
3 hours ago, meee39 said:

I have made every change you suggested (except for the type enum) although the blocks still seem to be turning into each other. I also installed WAILA to see if it was a graphical error or if the blocks were actually changing type; and they were.

We can't help with your updated code unless we know what has changed. This would be easiest if you create a github repository so you can push changes as you go along - but if not, then you need to post all of your updated code every time you change it and still need help.

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

    • that happens every time I enter a new dimension.
    • 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
  • Topics

×
×
  • Create New...

Important Information

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