Jump to content

Recommended Posts

Posted

I have made a very basic tile entity with a boolean and a getter function. But for some reason it always returns false, even though it really shouldn't.

 

Tile Entity code: 

public class TileEntityForge extends TileEntity implements ITickable {

    private boolean isWorking = false;
    private int smeltingTime = 1200;
    private int progress = 0;

    /*
     * Done S T save the progress
     */


    private ItemStackHandler inventory = new ItemStackHandler(1);

    @Override
    public NBTTagCompound writeToNBT(NBTTagCompound compound) {
        compound.setTag("inventory", inventory.serializeNBT());
        compound.setInteger("progress", progress);
        return super.writeToNBT(compound);
    }

    @Override
    public void readFromNBT(NBTTagCompound compound) {
        inventory.deserializeNBT(compound.getCompoundTag("inventory"));
        this.progress = compound.getInteger("progress");
        if(this.progress > 0){
            this.isWorking = true;
        }
        super.readFromNBT(compound);
    }

    @Override
    public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) {
        return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
    }

    @Nullable
    @Override
    public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) {
        return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ? (T)inventory : super.getCapability(capability, facing);
    }

    /*
     * Updates the block every tick
     * Converts bronze alloys into bronze ingots
     */

    @Override
    public void update() {
        //Checks if the Item in the slot is a bronze alloy
        if(inventory.getStackInSlot(0).getItem() == ModItems.bronze_alloy){
            //Checks if the forge is processing already
            if(this.isWorking){
                //Checks if finished, if so set the inventory to 4 bronze ingots and resets
                if(this.progress < 1){
                    inventory.setStackInSlot(0, new ItemStack(ModItems.bronze_ingot, 4));
                    this.isWorking = false;
                    this.progress = 0;
                    ExtraTools.logger.debug("finished!");

                    //else progresses
                }else {
                    this.progress--;
                    //this.spawnParticles(world, pos);
                    }


                //else starting the progress
            }else{
                this.isWorking = true;
                this.progress = this.smeltingTime;
                ExtraTools.logger.debug("start!");
            }

            //resets if there is no item and progress is being made
        } else if (this.isWorking) {
            this.isWorking = false;
            this.progress = 0;
        }
    }

    @SideOnly(Side.CLIENT)
    private void spawnParticles(World world, BlockPos pos){
        Random random = world.rand;
        Minecraft mc = Minecraft.getMinecraft();
        double d1 = (double) ((float) pos.getX() + random.nextFloat() / 2 + 0.25);
        double d2 = (double) ((float) pos.getY() + random.nextFloat());
        double d3 = (double) ((float) pos.getZ() + random.nextFloat() / 2 + 0.25);

        mc.world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d1, d2, d3, 0.0D, 0.0D, 0.0D, new int[0]);
    }


    //public function to check if the tile is busy
    public boolean isWorking(){
        ExtraTools.logger.error("TILE: " + this.isWorking);
        return this.isWorking;
    }


}

 

Block code:

public class BlockForge extends BlockTileEntity<TileEntityForge> {

    // 0 = north false
    // |
    // V
    // 7 = west true
    public static final String PROPERTY_NAME = "facing_active";
    public static final PropertyInteger PROPERTY = PropertyInteger.create(PROPERTY_NAME, 0, 7);


    public BlockForge(){
        super(Material.ROCK, Names.Blocks.FORGE);
        this.setTickRandomly(true);
        this.setDefaultState(this.getBlockState().getBaseState().withProperty(PROPERTY, 1));
    }

    /*
    * written on 17-01-19 by Axel and Bram on version 0.1
    *
    * this function triggers when you click on the block
    *
    * */

    /*
     * Done S T lock the inventory while working
     * Done S T lock the inventory to one bronze alloy
     * Done A T give a message when clicked while working or wrong item
     */

    @Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {


        //checks if the world is local or not
        if (!world.isRemote) {

            //gets the tile entity from the world position
            TileEntityForge tile = getTileEntity(world, pos);

            //checks if the tile is capable of handling items
            IItemHandler itemHandler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side);


            ExtraTools.logger.debug(itemHandler.getStackInSlot(0).getUnlocalizedName());
            ExtraTools.logger.debug(Names.Items.BRONZE_ALLOY);

            //checks if the player is sneaking
            if (!player.isSneaking()) {
                if(!tile.isWorking()) {

                    //checks if the players hand is empty
                    if (player.getHeldItem(hand).isEmpty()) {

                        //if player hand is empty and the player is not sneaking: gets the items from the tile and puts in in the hand of the player
                        player.setHeldItem(hand, itemHandler.extractItem(0, 64, false));

                    } else {
                        //checks if held items is bronze alloy
                        if (player.getHeldItem(hand).getItem() == ModItems.bronze_alloy) {
                            //if player hand is not empty, contains bronze alloy and the player is not sneaking: puts the item from the hand into the tile
                            itemHandler.insertItem(0, player.getHeldItem(hand).splitStack(1), false);
                        }else {
                            player.sendMessage(new TextComponentString("This machine only accepts bronze alloys."));
                        }
                    }

                    //makes sure the block is updated
                    tile.markDirty();
                } else {
                    player.sendMessage(new TextComponentString("This forge is currently in use!"));
                }


            } else {

                //get the stack from the tileEntity
                ItemStack stack = itemHandler.getStackInSlot(0);

                //if the stack is not empty
                if (!stack.isEmpty()) {

                    //if player is sneaking and the stack is not empty: converts the name of the item and displays it in the chat
                    String localized = ExtraTools.proxy.localize(stack.getUnlocalizedName() + ".name");
                    player.sendMessage(new TextComponentString(stack.getCount() + "x " + localized));

                } else {

                    //if player is sneaking and the stack is empty: display Empty in the chat
                    player.sendMessage(new TextComponentString("Empty"));
                }
            }
        }
        return true;
    }


    /*
     * Made by Axel and Bram on 17-01-19 version 0.1
     *
     * On block Broken Drop Items
     *
     */
    @Override
    public void breakBlock(World world, BlockPos pos, IBlockState state) {
        //gets the tileEntity from the world
        TileEntityForge tile = getTileEntity(world, pos);
        //checks if the tile is capable of handling items
        IItemHandler itemHandler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH);
        //gets the item from the tile
        ItemStack stack = itemHandler.getStackInSlot(0);
        //checks if the itemstack from the tile is not empty
        if (!stack.isEmpty()) {
            //if itemstack is not empty: drop new Item on the ground with same data
            EntityItem item = new EntityItem(world, pos.getX(), pos.getY(), pos.getZ(), stack);
            world.spawnEntity(item);
        }

        //breaks the block on pos
        super.breakBlock(world, pos, state);
    }



    @Override
    public Class<TileEntityForge> getTileEntityClass() {
        return TileEntityForge.class;
    }

    @Nullable
    @Override
    public TileEntityForge createTileEntity(World world, IBlockState state) {
        return new TileEntityForge();
    }

    @Override
    protected BlockStateContainer createBlockState() {
        return new BlockStateContainer(this, PROPERTY);
    }

    @Override
    public int getMetaFromState(IBlockState state) {
        return state.getValue(PROPERTY);
    }

    @Override
    public IBlockState getStateFromMeta(int meta) {
        return this.getDefaultState().withProperty(PROPERTY, meta);
    }

    @Override
    public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
        EnumFacing entityFacing = placer.getHorizontalFacing();
        int facing = 0;

        if(!world.isRemote) {

            if(entityFacing == EnumFacing.NORTH) {
                //south
                facing = 2;
            } else if(entityFacing == EnumFacing.EAST) {
                //west
                facing = 3;
            } else if(entityFacing == EnumFacing.SOUTH) {
                //north
                facing = 0;
            } else if(entityFacing == EnumFacing.WEST) {
                //east
                facing = 1;
            }

            world.setBlockState(pos, state.withProperty(PROPERTY, facing), 2);
        }
    }

    @Override
    public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {
        TileEntityForge tile = (TileEntityForge) worldIn.getTileEntity(pos);

        int facing = worldIn.getBlockState(pos).getValue(PROPERTY);

        if(rand.nextInt(2) == 0) {
            ExtraTools.logger.error(tile.isWorking());
        }

        if(rand.nextInt(8) == 0) {
            if (tile.isWorking()) {
                ExtraTools.logger.error("Working!");
                if (facing < 4) {
                    ExtraTools.logger.error("<4");
                    worldIn.setBlockState(pos, stateIn.withProperty(PROPERTY, facing + 4));
                }


                //worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX() + 0.5D, pos.getY() + 1.0D, pos.getZ() + 0.5D, 0.0D, 0.1D, 0.0D, new int[0]);
                //worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX() + 0.5D, pos.getY() + 1.0D, pos.getZ() + 0.5D, 0.0D, 0.1D, 0.0D, new int[0]);
                //worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, pos.getX() + 0.5D, pos.getY() + 1.0D, pos.getZ() + 0.5D, 0.0D, 0.1D, 0.0D, new int[0]);
            } else if (facing > 3) {
                worldIn.setBlockState(pos, stateIn.withProperty(PROPERTY, facing - 4));
            }
        }

    }

    @Override
    public boolean isTopSolid(IBlockState state) {
        return super.isTopSolid(state);
    }
}

 

SC: https://github.com/axel-wessels/ExtraTools

Forge version: 1.12.2-14.23.5.2768

 

Am I just stupid or is something going on here?

Posted
3 hours ago, STEENBRINK said:

extends BlockTileEntity<TileEntityForge>

You don't need this. Just override Block#hasTileEntity and Block#createTileEntity.

 

You don't need the boolean field in the first place.

What makes you think it always returns false? I suspect that you are trying to query it on the client which never has the synced data since you never sync your TE to the client.

 

3 hours ago, STEENBRINK said:

String localized = ExtraTools.proxy.localize(stack.getUnlocalizedName() + ".name"); player.sendMessage(new TextComponentString(stack.getCount() + "x " + localized));

Don't do this. TextComponentTranslation is a class that exists.

 

 

Posted
On 5/1/2019 at 5:02 PM, V0idWa1k3r said:

You don't need the boolean field in the first place.

What makes you think it always returns false? I suspect that you are trying to query it on the client which never has the synced data since you never sync your TE to the client.

So yeah, it returns false only in the randomDisplayTick, which is client side. How do I get the correct value to the client then?

I have no experience with this, sorry

Posted

See https://mcforge.readthedocs.io/en/latest/tileentities/tileentity/#synchronizing-the-data-to-the-client 

 

Personally, I'd go with a custom packet - NBT is a poor format for network communication (overly verbose), and a custom packet will be more efficient in terms of network traffic.

 

Also, I noticed you're using a PropertyInteger for your block's facing - why?? There's a builtin PropertyDirection class for exactly this (look at BlockFurnace for an example of a horizontally-constrained rotation, or BlockDispenser for an example of an unconstrained rotation). That would allow you to ditch that disgusting code in onBlockPlacedBy().

  • Thanks 1

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.