Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.12.2] [SOLVED] Problems With TileEntities and PropertyBools


Spacejet
 Share

Recommended Posts

using Forge 1.12.2

 

So I have a couple of problems to do with PropertyBool set on a block with a TileEntity. First problem is that the PropertyBool is not setting to it's default state on block placement, set in setDefaultState()

this.setDefaultState(this.blockState.getBaseState().withProperty(ACTIVATED, Boolean.valueOf(true)));

ACTIVATED is always false on placement, but, after a quick re-log (I don't restart minecraft, just the world) it changes to true.

 

Second Problem is that I don't know how to get and set the value of ACTIVATED from other classes, specifically in this case, the TileEntity class. I have tried everything, searched online, read the documentation but failed to find a mention on how to do it.

Full Block class:

Spoiler

package com.spacejet.quantivity.blocks;

import com.spacejet.quantivity.Main;
import com.spacejet.quantivity.tileentity.TileEntityEnergyAccumulator;
import com.spacejet.quantivity.util.handlers.GuiHandler;
import com.spacejet.quantivity.util.handlers.TileEntityHandler;

import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
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.World;

public class EnergyAccumulator extends BlockBase implements ITileEntityProvider
{

    public static final PropertyBool ACTIVATED = PropertyBool.create("activated");
    
    public EnergyAccumulator(String name, Material material) 
    {
        super(name, material);
        setHardness(5);
        setHarvestLevel("pickaxe", 2);
        setResistance(30);
        setSoundType(SoundType.METAL);
        setLightLevel(1);
        
        this.setDefaultState(this.blockState.getBaseState().withProperty(ACTIVATED, Boolean.valueOf(true)));
    }
    
    @Override
    public int getMetaFromState(IBlockState state) 
    {
        if(ACTIVATED.getAllowedValues().contains(true)) return 1;
        else return 0;
    }
    
    @Override
    public IBlockState getStateFromMeta(int meta)

    {
        if(meta == 1) return this.getDefaultState().withProperty(ACTIVATED, Boolean.valueOf(true));
        else return this.getDefaultState().withProperty(ACTIVATED, Boolean.valueOf(false));
    }
    
    @Override
    protected BlockStateContainer createBlockState() 
    {
        return new BlockStateContainer(this, new IProperty[] {ACTIVATED}); 
    }
    
    @Override
    public boolean hasTileEntity(IBlockState state) 
    {
        return true;
    }

    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta) 
    {
        return TileEntityHandler.ENERGY_ACCUMULATOR;
    }
    
    @Override
    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) 
    {
        if(!world.isRemote) 
        {
            playerIn.openGui(Main.instance, GuiHandler.ENERGY_ACCUMULATOR, world, pos.getX(), pos.getY(), pos.getZ());
        }
        
        return true;
    }

}

 

Full TileEntity class (note- I am using the CJCore Library in this mod)

Spoiler

package com.spacejet.quantivity.tileentity;

import cjminecraft.core.energy.EnergyUnit;
import cjminecraft.core.energy.EnergyUtils;
import cjminecraft.core.energy.compat.forge.CustomForgeEnergyStorage;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Biomes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;

public class TileEntityEnergyAccumulator extends TileEntity implements ITickable, ICapabilityProvider
{    
    private ItemStackHandler handler;
    private CustomForgeEnergyStorage storage;
    public static boolean active;
    
    public String name;
    
    private int energy;
    
    public TileEntityEnergyAccumulator(int maxInOut, int maxStore) 
    {
        this.handler = new ItemStackHandler(2);
        this.storage = new CustomForgeEnergyStorage(maxStore, 0);
        this.energy = storage.getEnergyStored();
    }
    
    @Override
    public void update() {
        if(this.world != null) 
        {
            if(!this.world.isRemote) 
            {
                if(this.world.getBiome(this.pos) == Biomes.PLAINS)
                {
                    if(active) {
                        this.storage.receiveEnergyInternal(60, false);
                    }
                }
                this.storage.extractEnergyInternal((int) EnergyUtils.giveEnergyAllFaces(this.world, this.pos, this.storage.getEnergyStored(), EnergyUnit.REDSTONE_FLUX, false, false), false);
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
        if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
            return (T) this.handler;
        
        if (capability == CapabilityEnergy.ENERGY)
            return (T) this.storage;
        
        return super.getCapability(capability, facing);
    }
    
    @Override
    public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
        if(capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
            return true;
        
        if(capability == CapabilityEnergy.ENERGY)
            return true;
        
        return super.hasCapability(capability, facing);
    }
    
    @Override
    public void readFromNBT(NBTTagCompound nbt) {
        this.storage.readFromNBT(nbt);
        active = nbt.getBoolean("active");
        super.readFromNBT(nbt);
    }
    
    @Override
    public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
        this.storage.writeToNBT(nbt);
        nbt.setBoolean("active", active);
        return super.writeToNBT(nbt);
    }
    
    @Override
    public ITextComponent getDisplayName() 
    {
        return new TextComponentTranslation("container.energy_accumulator.name");
    }
    
    public void setEnergy(int value)
    {
        this.energy = value;
    }
    
    public int getEnergy()
    {
        return this.energy;
    }
    
    public boolean isUsableByPlayer(EntityPlayer player) 
    {
        return this.world.getTileEntity(this.pos) != this ? false : player.getDistanceSq(this.pos.getX() + 0.5D, this.pos.getY() + 0.5D, this.pos.getZ() + 0.5D) <= 64.0D;
    }
}
 

NOTE- I have not set the value of active(In TE class) as I need to set it equal to ACTIVATED(PropBool in Block class), which I cannot find a way to do

 

Thanks for any help!

 

EDIT - After Reading 

I moved on from using 

ITileEntityProvider

to overriding 

hasTileEntity() and createTileEntity()

 

Edited by Spacejet
Marked as Solved
Link to comment
Share on other sites

3 hours ago, Spacejet said:

Boolean.valueOf(true)

Why are you using boxed values?

 

3 hours ago, Spacejet said:

extends BlockBase

BlockBase is an antipattern. There is already a BlockBase, it's called Block.

 

3 hours ago, Spacejet said:

@Override
    public int getMetaFromState(IBlockState state) 
    {
        if(ACTIVATED.getAllowedValues().contains(true)) return 1;
        else return 0;
    }

This will always return 1. Serialize the value of the property, not it's property.

 

3 hours ago, Spacejet said:

implements ITickable, ICapabilityProvider

TileEntity already implements ICapabilityProvider.

 

3 hours ago, Spacejet said:

public static boolean active;

Why is this static?

 

3 hours ago, Spacejet said:

if(this.world != null) 

This should never happen in onUpdate, and if it does some mod severely messes up and you should crash the game.

 

3 hours ago, Spacejet said:

active = nbt.getBoolean("active");

active is static though. Why are you (de)serializing it for instances?

 

3 hours ago, Spacejet said:

I don't know how to get and set the value of ACTIVATED from other classes, specifically in this case, the TileEntity class.

The same way you would do it in your block class. You have the world(TileEntity.world) and the position(TileEntity.pos). Get the blockstate from the world at position and change the value of the property in the same way you would for your block.

Link to comment
Share on other sites

@V0idWa1k3r the answer to your questions :

 

active is static because I was trying to set it in my block class as ACTIVATED was a part of my block class. I just forgot to change it back. Will do that.

 

I don't really know why I used boxed values when I could have simply used 'true' or 'false' ?

 

42 minutes ago, V0idWa1k3r said:
4 hours ago, Spacejet said:

mplements ITickable, ICapabilityProvider

TileEntity already implements ICapabilityProvider

I did not know that. Nice to know!

 

42 minutes ago, V0idWa1k3r said:
4 hours ago, Spacejet said:

I don't know how to get and set the value of ACTIVATED from other classes, specifically in this case, the TileEntity class.

The same way you would do it in your block class. You have the world(TileEntity.world) and the position(TileEntity.pos). Get the blockstate from the world at position and change the value of the property in the same way you would for your block

Is it with setBlockState() cause now I remember that I did not try that. Thanks a ton.

 

42 minutes ago, V0idWa1k3r said:
4 hours ago, Spacejet said:

extends BlockBase

BlockBase is an antipattern. There is already a BlockBase, it's called Block.

 

I call my Registry Handler and register all my blocks in this class.

 

42 minutes ago, V0idWa1k3r said:
4 hours ago, Spacejet said:

@Override
    public int getMetaFromState(IBlockState state) 
    {
        if(ACTIVATED.getAllowedValues().contains(true)) return 1;
        else return 0;
    }

This will always return 1. Serialize the value of the property, not it's property.

I just got to know about an hour ago that .contains() will search every possible output, not the selected. What should I use instead of that?? How do I get the value of the property in the first place?? getBlockState()?? But that returns a BlockStateContainer.

 

EDIT: I want to get its boolean value to set active equal to, but getBlockState() returns the state, not value! Right?

 

42 minutes ago, V0idWa1k3r said:

 

4 hours ago, Spacejet said:

if(this.world != null) 

This should never happen in onUpdate, and if it does some mod severely messes up and you should crash the game.

K. Will crash the game.

 

Thanks a lot for all those improvement tips and answers to some of my questions.

 

P.S: do you know why ACTIVATED returns false when block is first placed into the world? Set default state sets its default state to true!

Edited by Spacejet
More detail added
Link to comment
Share on other sites

4 minutes ago, Spacejet said:

I call my Registry Handler and register all my blocks in this class.

That sounds bad. That sound directly accessing the registry levels of bad. And potentially IHasModel levels of bad too.

 

5 minutes ago, Spacejet said:

How do I get the value of the property in the first place?? getBlockState()?? But that returns a BlockStateContainer.

IBlockState#getValue.

 

6 minutes ago, Spacejet said:

do you know why ACTIVATED returns false when block is first placed into the world? Set default state sets its default state to true!

I am not sure but you can override Block#getStateForPlacement and return the blockstate with the correct value.

 

7 minutes ago, Spacejet said:

Is it with setBlockState()

Yes, but you will need to override TileEntity#shouldRefresh in your TE class and make sure it returns false when the value of the property changes, but true otherwise or else the game will recreate your TE when you do that.

Link to comment
Share on other sites

6 minutes ago, V0idWa1k3r said:
10 minutes ago, Spacejet said:

do you know why ACTIVATED returns false when block is first placed into the world? Set default state sets its default state to true!

I am not sure but you can override Block#getStateForPlacement and return the blockstate with the correct value

Ok will try that.....sounds like it will work (hopefully)

 

6 minutes ago, V0idWa1k3r said:
10 minutes ago, Spacejet said:

How do I get the value of the property in the first place?? getBlockState()?? But that returns a BlockStateContainer.

IBlockState#getValue

Oh.

6 minutes ago, V0idWa1k3r said:
10 minutes ago, Spacejet said:

I call my Registry Handler and register all my blocks in this class.

That sounds bad. That sound directly accessing the registry levels of bad. And potentially IHasModel levels of bad too

 

I regret writing that as I am not on my computer and cannot check to make sure what I wrote was correct as that is what I thought I was doing in blockbase..... what should I do if I was doing the bad thing?

Edited by Spacejet
Spelling mistake
Link to comment
Share on other sites

4 minutes ago, Spacejet said:

what should I do if I was doing the bad thing?

Don't directly access the registry, register your things in the appropriate RegistryEvent.Register, in this case it would be Register<Block>.

In case of IHasModel - get rid of it and just register your models directly in the ModelRegistryEvent.

  • Like 1
Link to comment
Share on other sites

3 hours ago, Spacejet said:

Oh then it's fine as I am indeed using registryevents.. phew.. scared me real good.

Are you instantiating your objects in their registry events?

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

13 hours ago, Cadiboo said:

Are you instantiating your objects in their registry events?

Yes. I am just adding the blocks extend blockbase to a list and then that list is passed on to the onBlockRegister() event

BlockBase:

Spoiler

package com.spacejet.quantivity.blocks;

import com.spacejet.quantivity.Main;
import com.spacejet.quantivity.init.ModBlocks;
import com.spacejet.quantivity.init.ModItems;
import com.spacejet.quantivity.util.IHasModel;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;

public class BlockBase extends Block implements IHasModel{
    
    public BlockBase(String name, Material material) {
        
        super(material);
        setUnlocalizedName(name);
        setRegistryName(name);
        
        ModBlocks.BLOCKS.add(this);
        ModItems.ITEMS.add(new ItemBlock(this).setRegistryName(this.getRegistryName()));
        
    }

    @Override
    public void registerModels() {
        
        Main.proxy.registerItemRenderer(Item.getItemFromBlock(this), 0, "inventory");
        
    }
}
 

 

RegistryHandler:

Spoiler

package com.spacejet.quantivity.util.handlers;

import com.spacejet.quantivity.Main;
import com.spacejet.quantivity.init.ModBiomes;
import com.spacejet.quantivity.init.ModBlocks;
import com.spacejet.quantivity.init.ModItems;
import com.spacejet.quantivity.util.IHasModel;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;

@EventBusSubscriber
public class RegistryHandler {

    @SubscribeEvent
    public static void onItemRegister(RegistryEvent.Register<Item> event) {
        
        event.getRegistry().registerAll(ModItems.ITEMS.toArray(new Item[0]));
        
    }
    
    @SubscribeEvent
    public static void onBlockRegister(RegistryEvent.Register<Block> event) {
        
        event.getRegistry().registerAll(ModBlocks.BLOCKS.toArray(new Block[0]));
    }
    
    @SubscribeEvent
    public static void onModelRegister(ModelRegistryEvent event) {
        
        for(Item item : ModItems.ITEMS) {
            
            if(item instanceof IHasModel) {
                ((IHasModel)item).registerModels();
            }    
        }
        
        for(Block block : ModBlocks.BLOCKS) {
            
            if(block instanceof IHasModel) {
                ((IHasModel)block).registerModels();
            }    
        }
    }
    
    public static void preInitRegistries() 
    {
        ModBiomes.registerBiomes();
        TileEntityHandler.RegisterTileEntities();
    }
    
    public static void initRegisteries() 
    {
        NetworkRegistry.INSTANCE.registerGuiHandler(Main.instance, new GuiHandler());
    }
}

 

Link to comment
Share on other sites

26 minutes ago, Spacejet said:

IHasModel

Did you remove this like voidwaker said?

26 minutes ago, Spacejet said:

Yes. I am just adding the blocks extend blockbase to a list and then that list is passed on to the onBlockRegister() event

Where are you instantiating(calling the constructor) for them? Also you shouldn't have a BlockBase class when you instantiate them add them to the list like so

list.add(new Block(...).set...);

Or even 

RegistryObject registry = event.getRegistry

registry.register(new Block(...).set...);

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

9 minutes ago, Animefan8888 said:
39 minutes ago, Spacejet said:

Yes. I am just adding the blocks extend blockbase to a list and then that list is passed on to the onBlockRegister() event

Where are you instantiating(calling the constructor) for them

This is my Mod Blocks class which has the list I am adding the blocks into

Spoiler

package com.spacejet.quantivity.init;

import java.util.ArrayList;
import java.util.List;

import com.spacejet.quantivity.blocks.CrystalBlock;
import com.spacejet.quantivity.blocks.EnergyAccumulator;
import com.spacejet.quantivity.blocks.Lantern;
import com.spacejet.quantivity.blocks.TitaniumBlock;
import com.spacejet.quantivity.blocks.TitaniumOre;
import com.spacejet.quantivity.blocks.material.ModMaterial;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

public class ModBlocks {
    
    public static final List<Block> BLOCKS = new ArrayList<Block>();
    
    public static final Block TITANIUM_BLOCK = new TitaniumBlock("titanium_block", Material.IRON);
    public static final Block BLUE_CRYSTAL_BLOCK = new CrystalBlock("blue_crystal_block", Material.GLASS);
    public static final Block RED_CRYSTAL_BLOCK = new CrystalBlock("red_crystal_block", Material.GLASS);
    public static final Block TITANIUM_ORE = new TitaniumOre("titanium_ore", Material.ROCK);
    public static final Block LANTERN = new Lantern("lantern", ModMaterial.LANTERN);
    
    //Energy Blocks
    public static final Block ENERGY_ACCUMULATOR = new EnergyAccumulator("energy_accumulator", Material.IRON);
}
 

The constructors are called in the class above as you can see..

Edited by Spacejet
grammar imperfections
Link to comment
Share on other sites

1 hour ago, Spacejet said:

public static final Block TITANIUM_BLOCK = new TitaniumBlock("titanium_block", Material.IRON);

Dont do this, this is a static initializer you shouldn't do this with any IForgeRegistryEntry object. Ie anything that has a registry event. They should be initialized in the registryEvent where you register them.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Link to comment
Share on other sites

1 hour ago, Animefan8888 said:

Dont do this, this is a static initializer you shouldn't do this with any IForgeRegistryEntry object. Ie anything that has a registry event. They should be initialized in the registryEvent where you register them.

How would you do that?

Link to comment
Share on other sites

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
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.

 Share



  • Recently Browsing

    No registered users viewing this page.

  • Posts

    • I keep getting the following error when I try to start up minecraft. Brief report: I already tried to uninstall forge and download it again, uninstall the mods and download others, I changed the version (before 1.17.1 to 1.18.1), I already deleted the phrase "forge-common.toml of type COMMON for modid forge" and even saving it magically returned to the report.  I also put the crash report here.
    • Hello, I'm trying to make a forge server for me and a few friends to play on. Generally this goes over without too many problems but just recently when i was trying to make a new modpack the server wouldnt start, so I went through removing mods until I could find the error and as it turned out no mods were erroring, as just lone forge wouldnt start. the error I seem to be getting is "19.01 21:59:37 [Server] INFO ERROR StatusLogger Reconfiguration failed: No configuration found for '232204a1' at 'null' in 'null'" I have no idea what this means but after this the console wont send any messages other than "Auto-saving world..." after a couple minutes, and when out of curiosity I tried to join on a client it acted like the server was up but I could not join and there was no response console side from me trying to do so. It does recieve stop and start commands fine though. Thank you
    • Any help or advice would be appreciated. I'm trying to learn how to add particles to a mod, using a tutorial from TheGreyGhost. Trying to get the particle to appear in the Entity's tick() method. The vanilla FLAME particle appears but not my particle. @Override public void tick() { if(entity == null) return; try { // Adds a particle to every entity while in the overworld! //this.level.addParticle(ParticleTypes.FLAME, this.getX(), this.getY() + 1, this.getZ(), 0, 0.04, 0); // Try to add a custom particle to every entity in the overworld. Color tint = Color.CYAN; // does this do anything if the particle texture is already colored? double diameter = this.getEntityScale(); FlameParticleData flameParticleData = new FlameParticleData(tint, diameter); this.level.addParticle(flameParticleData, this.getX(), this.getY() + 2, this.getZ(), 0, 0.05, 0); } catch (Exception e) { The other code I have setting up the Particle Registration, the FlameParticle, the FlameParticleData, the FlameParticleFactory, and the FlameParticleType: ParticleRegistration.java. I also have a flame_particle.json that references the flame.png that I want to use. @Mod.EventBusSubscriber(modid = MyMod.MODID, bus = Bus.MOD, value = Dist.CLIENT) public class ParticleRegistration { public static final DeferredRegister<ParticleType<?>> PARTICLES_TYPES = DeferredRegister.create( ForgeRegistries.PARTICLE_TYPES, MyMod.MODID); // This sets the FlameParticleType to use the textures specified in flame_particle.json. public static final RegistryObject<ParticleType<FlameParticleData>> FLAME_PARTICLE = PARTICLES_TYPES.register( "flame_particle", FlameParticleType::new); // Is this necessary? public static ParticleType<FlameParticleData> flameParticleType = new FlameParticleType(); @SuppressWarnings("resource") @SubscribeEvent public static void registerParticleFactory(ParticleFactoryRegisterEvent event) { Minecraft.getInstance().particleEngine.register(ParticleRegistration.FLAME_PARTICLE.get(), FlameParticleFactory::new); } } FlameParticle.java /** * Based on TheGreyGhost's MinecraftByExample * Custom Particle to illustrate how to add a Particle with your own texture and movement/animation behaviour * */ public class FlameParticle extends SpriteTexturedParticle { /** * Construct a new FlameParticle at the given [x,y,z] position, with the given initial velocity, the given color, and the * given diameter. * We also supply sprites so that you can change the sprite texture in the tick() method (although not needed for this example) */ public FlameParticle(ClientWorld world, double x, double y, double z, double velocityX, double velocityY, double velocityZ, Color tint, double diameter, IAnimatedSprite sprites) { super(world, x, y, z, velocityX, velocityY, velocityZ); this.sprites = sprites; setColor(tint.getRed()/255.0F, tint.getGreen()/255.0F, tint.getBlue()/255.0F); setSize((float)diameter, (float)diameter); // the size (width, height) of the collision box. final float PARTICLE_SCALE_FOR_ONE_METRE = 0.5F; // if the particleScale is 0.5, the texture will be rendered as 1 metre high // sets the rendering size of the particle for a TexturedParticle. this.scale(PARTICLE_SCALE_FOR_ONE_METRE * (float)diameter); //maxAge = 100; // lifetime in ticks: 100 ticks = 5 seconds this.lifetime = 100; final float ALPHA_VALUE = 1.0F; this.alpha = ALPHA_VALUE; //the vanilla Particle constructor added random variation to our starting velocity. Undo it! this.xd = velocityX; this.yd = velocityY; this.zd = velocityZ; // the move() method will check for collisions with scenery this.hasPhysics = true; // I think hasPhysics replaces canCollide } // Comments from TheGreyGhost // ---- methods used by TexturedParticle.renderParticle() method to find out how to render your particle // the base method just renders a quad, rotated to directly face the player // can be used to change the skylight+blocklight brightness of the rendered Particle. @Override public int getLightColor(float partialTick) // previously protected int getBrightnessForRender(float partialTick) { final int BLOCK_LIGHT = 15; // maximum brightness final int SKY_LIGHT = 15; // maximum brightness final int FULL_BRIGHTNESS_VALUE = LightTexture.pack(BLOCK_LIGHT, SKY_LIGHT); // .pack replaces .packLight return FULL_BRIGHTNESS_VALUE; // if you want the brightness to be the local illumination (from block light and sky light) you can just use // the Particle.getBrightnessForRender() base method, which contains: // BlockPos blockPos = new BlockPos(this.posX, this.posY, this.posZ); // return this.world.isBlockLoaded(blockPos) ? WorldRenderer.getCombinedLight(this.world, blockPos) : 0; } // Choose the appropriate render type for your particles: // There are several useful predefined types: // PARTICLE_SHEET_TRANSLUCENT semi-transparent (translucent) particles // PARTICLE_SHEET_OPAQUE opaque particles // TERRAIN_SHEET particles drawn from block or item textures // PARTICLE_SHEET_LIT appears to be the same as OPAQUE. Not sure of the difference. In previous versions of minecraft, // "lit" particles changed brightness depending on world lighting i.e. block light + sky light public IParticleRenderType getRenderType() { return IParticleRenderType.PARTICLE_SHEET_TRANSLUCENT; } /** * call once per tick to update the Particle position, calculate collisions, remove when max lifetime is reached, etc */ @Override public void tick() { // if you want to change the texture as the particle gets older, you can use //setSpriteFromAge(sprites); // not sure whether this should be uncommented yet this.xo = x; // previously prevPosX and posX this.yo = y; // previously prevPosY and posY this.xo = z; // previously prevPosZ and posZ move(xd, yd, zd); // simple linear motion. You can change speed by changing xd, yd, // zd every tick. For example - you can make the particle accelerate downwards due to gravity by // final double GRAVITY_ACCELERATION_PER_TICK = -0.02; // yd += GRAVITY_ACCELERATION_PER_TICK; // calling move() also calculates collisions with other objects // collision with a block makes the ball disappear. But does not collide with entities if (onGround) { // onGround is only true if the particle collides while it is moving downwards... this.remove(); // this.setExpired() is probably this.remove() } if (yo == y && yd > 0) { // detect a collision while moving upwards (can't move up at all) this.remove(); } if (this.age++ >= this.lifetime) { // this.maxAge becomes this.lifetime this.remove(); } } private final IAnimatedSprite sprites; // contains a list of textures; choose one using either // newParticle.selectSpriteRandomly(sprites); or newParticle.selectSpriteWithAge(sprites); } FlameParticleData.java /** * Based on TheGreyGhost's MinecraftByExample * The particle has two pieces of information which are used to customise it: * * 1) The colour (tint) which is used to change the hue of the particle * 2) The diameter of the particle * * This class is used to * 1) store this information, and * 2) transmit it between server and client (write and read methods), and * 3) parse it from a command string i.e. the /particle params */ public class FlameParticleData implements IParticleData { public FlameParticleData(Color tint, double diameter) { this.tint = tint; this.diameter = constrainDiameterToValidRange(diameter); } public Color getTint() { return tint; } /** * @return get diameter of particle in metres */ public double getDiameter() { return diameter; } @Nonnull @Override public ParticleType<FlameParticleData> getType() { return ParticleRegistration.flameParticleType; } // write the particle information to a PacketBuffer, ready for transmission to a client @Override public void writeToNetwork(PacketBuffer buf) { buf.writeInt(tint.getRed()); buf.writeInt(tint.getGreen()); buf.writeInt(tint.getBlue()); buf.writeDouble(diameter); } // used for debugging I think; prints the data in human-readable format @Nonnull @Override public String writeToString() { return String.format(Locale.ROOT, "%s %.2f %i %i %i", this.getType().getRegistryName(), diameter, tint.getRed(), tint.getGreen(), tint.getBlue()); } private static double constrainDiameterToValidRange(double diameter) { final double MIN_DIAMETER = 0.05; final double MAX_DIAMETER = 1.0; return MathHelper.clamp(diameter, MIN_DIAMETER, MAX_DIAMETER); } private Color tint; private double diameter; // Comments from the TheGreyGhost // --------- these remaining methods are used to serialize the Particle Data. // I'm not yet sure what the Codec is used for, given that the DESERIALIZER already deserializes using read. // Perhaps it will be used to replace the manual read methods in the future. // The CODEC is a convenience to make it much easier to serialise and deserialise your objects. // Using the builder below, you construct a serialiser and deserialiser in one go, using lambda functions. // eg for the FlameParticleData CODEC: // a) In order to serialise it, it reads the 'tint' member variable (type: INT) and the 'diameter' member variable (type: DOUBLE) // b) In order to deserialise it, call the matching constructor FlameParticleData(INT, DOUBLE) public static final Codec<FlameParticleData> CODEC = RecordCodecBuilder.create( instance -> instance.group( Codec.INT.fieldOf("tint").forGetter(d -> d.tint.getRGB()), Codec.DOUBLE.fieldOf("diameter").forGetter(d -> d.diameter) ).apply(instance, FlameParticleData::new) ); private FlameParticleData(int tintRGB, double diameter) { this.tint = new Color(tintRGB); this.diameter = constrainDiameterToValidRange(diameter); } // The DESERIALIZER is used to construct FlameParticleData from either command line parameters or from a network packet public static final IDeserializer<FlameParticleData> DESERIALIZER = new IDeserializer<FlameParticleData>() { // parse the parameters for this particle from a /particle command @Nonnull @Override public FlameParticleData fromCommand(@Nonnull ParticleType<FlameParticleData> type, @Nonnull StringReader reader) throws CommandSyntaxException { reader.expect(' '); double diameter = constrainDiameterToValidRange(reader.readDouble()); final int MIN_COLOUR = 0; final int MAX_COLOUR = 255; reader.expect(' '); int red = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); reader.expect(' '); int green = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); reader.expect(' '); int blue = MathHelper.clamp(reader.readInt(), MIN_COLOUR, MAX_COLOUR); Color color = new Color(red, green, blue); return new FlameParticleData(color, diameter); } // read the particle information from a PacketBuffer after the client has received it from the server @Override public FlameParticleData fromNetwork(@Nonnull ParticleType<FlameParticleData> type, PacketBuffer buf) { // warning! never trust the data read in from a packet buffer. final int MIN_COLOUR = 0; final int MAX_COLOUR = 255; int red = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); int green = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); int blue = MathHelper.clamp(buf.readInt(), MIN_COLOUR, MAX_COLOUR); Color color = new Color(red, green, blue); double diameter = constrainDiameterToValidRange(buf.readDouble()); return new FlameParticleData(color, diameter); } }; } FlameParticleFactory.java /** * Based on TheGreyGhost's MinecraftByExample * On the client side: * When the client wants to spawn a Particle, it gives the FlameParticleData to this factory method * The factory selects an appropriate Particle class and instantiates it * */ public class FlameParticleFactory implements IParticleFactory<FlameParticleData> { //IParticleFactory private final IAnimatedSprite sprites; // contains a list of textures; choose one using either // not sure if i still need this // newParticle.selectSpriteRandomly(sprites); or newParticle.selectSpriteWithAge(sprites); // this method is needed for proper registration of your Factory: // The ParticleManager.register method creates a Sprite and passes it to your factory for subsequent use when rendering, then // populates it with the textures from your textures/particle/xxx.json public FlameParticleFactory(IAnimatedSprite sprite) { this.sprites = sprite; } @Nullable @Override public Particle createParticle(FlameParticleData flameParticleData, ClientWorld world, double xPos, double yPos, double zPos, double xVelocity, double yVelocity, double zVelocity) { FlameParticle newParticle = new FlameParticle(world, xPos, yPos, zPos, xVelocity, yVelocity, zVelocity, flameParticleData.getTint(), flameParticleData.getDiameter(), sprites); newParticle.pickSprite(sprites); // not quite the newParticle.selectSpriteRandomly(sprites) that was used. return newParticle; } // This is private to prevent you accidentally registering the Factory using the default constructor. // ParticleManager has two register methods, and if you use the wrong one the game will enter an infinite loop private FlameParticleFactory() { throw new UnsupportedOperationException("Use the FlameParticleFactory(IAnimatedSprite sprite) constructor"); } } FlameParticleType.java /** * Based on TheGreyGhost's MinecraftByExample * Simple class used to describe the Particle */ public class FlameParticleType extends ParticleType<FlameParticleData> { private static boolean ALWAYS_SHOW_REGARDLESS_OF_DISTANCE_FROM_PLAYER = false; public FlameParticleType() { super(ALWAYS_SHOW_REGARDLESS_OF_DISTANCE_FROM_PLAYER, FlameParticleData.DESERIALIZER); } // get the Codec used to // a) convert a FlameParticleData to a serialised format // b) construct a FlameParticleData object from the serialised format public Codec<FlameParticleData> codec() { return FlameParticleData.CODEC; } } The flame_particle.json, which is located in resources/asset.MyMod/particles, that references the flame.png, located in resources/asset.MyMod/particles/textures/particles { "textures": [ "MyMod:flame" ] }  
    • How did you figure out the texture changing? I looked at your code and I can't seem to replicate your solution.
    • Forge won't launch on minecraft 1.16.5  I already used --add-exports=java.base/sun.security.util=ALL-UNNAMED --add-opens=java.base/java.util.jar=ALL-UNNAMED and didn't work, I also tried changing my JMV to C:\Program Files\Java\jre1.8.0_321\bin\javaw.exe, C:\Program Files\Java\jre1.8.0_321\bin\java.exe, C:\Program Files\Java\jre1.8.0_321\bin\java.exe and didn't work and my Java version is 8 This is my error log  System info:   Operating system:     OSFullName: Microsoft Windows 10 Home Single Language     Build: 9200     Is64BitOperatingSystem: True   Java path: 'C:\Program Files\Java\jre1.8.0_321' (64-bit) Process info:   Minecraft version/type: 1.16.5-forge-36.2.20/release   Executable file: 'C:\Program Files\Java\jre1.8.0_321\bin\javaw.exe'   Arguments: '-XX:+IgnoreUnrecognizedVMOptions --add-exports=java.base/sun.security.util=ALL-UNNAMED --add-exports=jdk.naming.dns/com.sun.jndi.dns=java.naming --add-opens=java.base/java.util.jar=ALL-UNNAMED -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump "-Dos.name=Windows 10" -Dos.version=10.0 -Djava.library.path=C:\Users\agatt\AppData\Roaming\.minecraft\natives -Dminecraft.launcher.brand="Minecraft Launcher" -Dminecraft.launcher.version=3.9.5_. -cp C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\forge\1.16.5-36.2.20\forge-1.16.5-36.2.20.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm\9.1\asm-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-commons\9.1\asm-commons-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-tree\9.1\asm-tree-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-util\9.1\asm-util-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\ow2\asm\asm-analysis\9.1\asm-analysis-9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\cpw\mods\modlauncher\8.0.9\modlauncher-8.0.9.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\cpw\mods\grossjava9hacks\1.3.3\grossjava9hacks-1.3.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\accesstransformers\3.0.1\accesstransformers-3.0.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\antlr\antlr4-runtime\4.9.1\antlr4-runtime-4.9.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\eventbus\4.0.0\eventbus-4.0.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\forgespi\3.2.0\forgespi-3.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\coremods\4.0.6\coremods-4.0.6.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\unsafe\0.2.0\unsafe-0.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\electronwill\night-config\core\3.6.3\core-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\electronwill\night-config\toml\3.6.3\toml-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\jline\jline\3.12.1\jline-3.12.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\maven\maven-artifact\3.6.3\maven-artifact-3.6.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\jodah\typetools\0.8.3\typetools-0.8.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-api\2.15.0\log4j-api-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.15.0\log4j-core-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-slf4j18-impl\2.15.0\log4j-slf4j18-impl-2.15.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecrell\terminalconsoleappender\1.2.0\terminalconsoleappender-1.2.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\5.0.4\jopt-simple-5.0.4.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\spongepowered\mixin\0.8.4\mixin-0.8.4.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\minecraftforge\nashorn-core-compat\15.1.1.1\nashorn-core-compat-15.1.1.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\patchy\1.3.9\patchy-1.3.9.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\dev\jna\jna\4.4.0\jna-4.4.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\ibm\icu\icu4j\66.1\icu4j-66.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\javabridge\1.0.22\javabridge-1.0.22.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\sf\jopt-simple\jopt-simple\5.0.3\jopt-simple-5.0.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\io\netty\netty-all\4.1.25.Final\netty-all-4.1.25.Final.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\google\guava\guava\21.0\guava-21.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-lang3\3.5\commons-lang3-3.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-io\commons-io\2.5\commons-io-2.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-codec\commons-codec\1.10\commons-codec-1.10.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\brigadier\1.0.17\brigadier-1.0.17.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\datafixerupper\4.0.26\datafixerupper-4.0.26.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\google\code\gson\gson\2.8.0\gson-2.8.0.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\authlib\2.1.28\authlib-2.1.28.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\it\unimi\dsi\fastutil\8.2.1\fastutil-8.2.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-api\2.8.1\log4j-api-2.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\apache\logging\log4j\log4j-core\2.8.1\log4j-core-2.8.1.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\3.2.2\lwjgl-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-jemalloc\3.2.2\lwjgl-jemalloc-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-openal\3.2.2\lwjgl-openal-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-opengl\3.2.2\lwjgl-opengl-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-glfw\3.2.2\lwjgl-glfw-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-stb\3.2.2\lwjgl-stb-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-tinyfd\3.2.2\lwjgl-tinyfd-3.2.2.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\3.2.2\lwjgl-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-jemalloc\3.2.2\lwjgl-jemalloc-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-openal\3.2.2\lwjgl-openal-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-opengl\3.2.2\lwjgl-opengl-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-glfw\3.2.2\lwjgl-glfw-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-tinyfd\3.2.2\lwjgl-tinyfd-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl-stb\3.2.2\lwjgl-stb-3.2.2-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\text2speech\1.11.3\text2speech-1.11.3.jar;C:\Users\agatt\AppData\Roaming\.minecraft\libraries\com\mojang\text2speech\1.11.3\text2speech-1.11.3-natives-windows.jar;C:\Users\agatt\AppData\Roaming\.minecraft\versions\1.16.5\1.16.5.jar cpw.mods.modlauncher.Launcher --launchTarget fmlclient --fml.forgeVersion 36.2.20 --fml.mcVersion 1.16.5 --fml.forgeGroup net.minecraftforge --fml.mcpVersion 20210115.111550 --username zach --version "Minecraft Launcher" --gameDir C:\Users\agatt\AppData\Roaming\.minecraft --assetsDir C:\Users\agatt\AppData\Roaming\.minecraft\assets --assetIndex 1.16 --uuid d61616c3e2a6cf59a0cc435a66c091d4    Exit code: 1 //Finished printing debug information ============    
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

By using this site, you agree to our Privacy Policy.