Jump to content

Recommended Posts

Posted

I have tried using getEntityAttribute(SharedMonsterAttributes.maxHealth); but that returns this "net.minecraft.entity.ai.attributes.ModifiableAttributeInstance@59721257"

Posted

Try and get an instance of the entity.

To get the max hp use Entity#getMaxHealth() but set it as an int (casting).

Java automatically rounds up from that float (like before casting).

 

int maxHealth = entity.getMaxHealth();

Posted

I'm doing it a completely different way because I want to make sure that I can change keep the max health after the player leaves the world so I am now using a class that extends IExtendedEntityProperties. What I have done for all my other values works fine but when I put a variable inside of this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth) like this instead of just a double (this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth)), the entity dies immediately (so the maxHealth is 0) even though when I check my classes it is set to a base of 10.0D. Here are the classes use:

 

The entities class.

 

 

package com.blocklings.entity;

 

import net.minecraft.entity.Entity;

import net.minecraft.entity.EntityAgeable;

import net.minecraft.entity.EntityLivingBase;

import net.minecraft.entity.SharedMonsterAttributes;

import net.minecraft.entity.ai.EntityAIAttackOnCollide;

import net.minecraft.entity.ai.EntityAIAvoidEntity;

import net.minecraft.entity.ai.EntityAIFollowOwner;

import net.minecraft.entity.ai.EntityAIOwnerHurtByTarget;

import net.minecraft.entity.ai.EntityAIOwnerHurtTarget;

import net.minecraft.entity.ai.EntityAIWander;

import net.minecraft.entity.ai.EntityAIWatchClosest;

import net.minecraft.entity.passive.EntityTameable;

import net.minecraft.entity.player.EntityPlayer;

import net.minecraft.init.Blocks;

import net.minecraft.item.Item;

import net.minecraft.item.ItemStack;

import net.minecraft.pathfinding.PathEntity;

import net.minecraft.util.ChatComponentText;

import net.minecraft.util.DamageSource;

import net.minecraft.world.World;

 

import com.blocklings.network.CreatePacketServerSide;

import com.blocklings.stats.BlocklingStats;

 

import cpw.mods.fml.client.FMLClientHandler;

import cpw.mods.fml.relauncher.Side;

import cpw.mods.fml.relauncher.SideOnly;

 

public class EntityBlockling extends EntityTameable {

 

public BlocklingStats properties = BlocklingStats.get(this);

public double maxHealth = properties.getMaxHealth();

 

public EntityBlockling(World world) {

 

super(world);

 

this.setSize(0.91F, 0.91F);

this.getNavigator().setAvoidsWater(true);

this.getNavigator().setCanSwim(false);

this.tasks.addTask(0, new EntityAIAttackOnCollide(this, 1.0D, true));

this.tasks.addTask(1, new EntityAIWatchClosest(this, EntityPlayer.class, 16.0F));

        this.tasks.addTask(2, new EntityAIFollowOwner(this, 1.0D, 8.0F, 5.0F));

        this.tasks.addTask(3, this.aiSit);

        this.tasks.addTask(4, new EntityAIAvoidEntity(this, EntityPlayer.class, 16.0F, 1.5D, 1.5D));

        this.tasks.addTask(5, new EntityAIWander(this, 1.0D));

        this.targetTasks.addTask(0, new EntityAIOwnerHurtByTarget(this));

        this.targetTasks.addTask(1, new EntityAIOwnerHurtTarget(this));

        this.targetTasks.addTask(2, new EntityAIAttackOnCollide(this, 1.0D, true));

        this.setTamed(false);

       

}

 

protected void applyEntityAttributes() {

 

super.applyEntityAttributes();

this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth);

this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);

this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);

    this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D);

 

}

 

public boolean interact(EntityPlayer par1EntityPlayer)

    {

        ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem();

       

        if (itemstack != null && itemstack.getItem() == Item.getItemFromBlock(Blocks.red_flower))

        {

            if (!par1EntityPlayer.capabilities.isCreativeMode)

            {

                --itemstack.stackSize;

            }

 

            if (itemstack.stackSize <= 0)

            {

                par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, (ItemStack)null);

            }

 

            if (par1EntityPlayer.getCommandSenderName().equalsIgnoreCase(this.getOwnerName()) && !this.worldObj.isRemote)

            {

                this.aiSit.setSitting(!this.isSitting());

                this.isJumping = false;

                this.setPathToEntity((PathEntity)null);

                this.setTarget((Entity)null);

                this.setAttackTarget((EntityLivingBase)null);

                FMLClientHandler.instance().getClient().ingameGUI.getChatGUI().printChatMessage(new ChatComponentText("XP: " + Integer.toString(properties.getXP()) + "/" + properties.getRequiredXP() + " | " + "Level: " + properties.getLevel() + " | " + "Health: " + this.getHealth() + "/" + (int)properties.getMaxHealth()));

            }

           

            if (!this.worldObj.isRemote && !this.isTamed())

            {

                if (this.rand.nextInt(3) == 0)

                {

                    this.setTamed(true);

                    this.setPathToEntity((PathEntity)null);

                    this.setAttackTarget((EntityLivingBase)null);

                    this.setOwner(par1EntityPlayer.getCommandSenderName());

                    this.playTameEffect(true);

                    this.aiSit.setSitting(!this.isSitting());

                    this.worldObj.setEntityState(this, (byte)7);

                }

                else

                {

                    this.playTameEffect(false);

                    this.worldObj.setEntityState(this, (byte)6);

                }

            }

 

            return true;

        }

 

        return super.interact(par1EntityPlayer);

    }

 

public boolean attackEntityAsMob(Entity par1Entity) {

 

properties.addXP(50);

 

        return par1Entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue());

       

}

 

@SideOnly(Side.CLIENT)

    public int getLevel() {

 

        return properties.getLevel();

       

    }

 

@Override

public EntityAgeable createChild(EntityAgeable var1) {

 

return null;

 

}

 

public boolean isAIEnabled() {

 

return true;

 

}

 

}

 

 

 

 

package com.blocklings.stats;

 

import net.minecraft.entity.Entity;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.world.World;

import net.minecraftforge.common.IExtendedEntityProperties;

import net.minecraftforge.event.entity.living.LivingAttackEvent;

 

import com.blocklings.entity.EntityBlockling;

 

import cpw.mods.fml.common.eventhandler.SubscribeEvent;

 

public class BlocklingStats implements IExtendedEntityProperties {

 

public final static String EXT_PROP_NAME = "BlocklingXP";

 

public EntityBlockling blockling;

public int xp = 0;

public int level = 1;

public int requiredXP = 256;

public double maxHealth = 10.0D;

 

public BlocklingStats(EntityBlockling blockling) {

 

this.blockling = blockling;

 

}

 

public static final void register(EntityBlockling blockling) {

 

blockling.registerExtendedProperties(BlocklingStats.EXT_PROP_NAME, new BlocklingStats(blockling));

 

}

 

public static final BlocklingStats get(EntityBlockling entity) {

 

return (BlocklingStats) entity.getExtendedProperties(EXT_PROP_NAME);

 

}

 

@Override

public void saveNBTData(NBTTagCompound compound) {

 

compound.setInteger("xp", this.xp);

compound.setInteger("level", this.level);

compound.setInteger("requiredXP", this.requiredXP);

compound.setDouble("maxHealth", this.maxHealth);

 

}

 

@Override

public void loadNBTData(NBTTagCompound compound) {

 

this.xp = compound.getInteger("xp");

this.level = compound.getInteger("level");

this.requiredXP = compound.getInteger("requiredXP");

this.maxHealth = compound.getDouble("maxHealth");

 

}

 

@Override

public void init(Entity entity, World world) {

 

 

 

}

 

public void addXP(int addedXP) {

 

xp = xp + addedXP;

onLevelUp();

 

}

 

public void onLevelUp() {

 

if(xp >= requiredXP) {

 

this.xp = 0;

this.level++;

calculateRequiredXP();

 

}

 

}

 

public void calculateRequiredXP() {

 

this.requiredXP = level * level * 8 * (8 + level);

 

}

 

public int getXP() {

 

return xp;

 

}

 

public int getRequiredXP() {

 

return requiredXP;

 

}

 

public int getLevel() {

 

return level;

 

}

 

public double getMaxHealth() {

 

return maxHealth;

 

}

 

}

 

Posted

Okay, the problem is your initialization of the properties field.  You're initializing with:

public BlocklingStats properties = BlocklingStats.get(this);

But that is a class field before you've called the constructor.  In other words, I don't think there really is a "this" at that point ot pass to the BlockingState.get() method.

You might be able to do this by calling the method within the constructor instead.

 

In any case, I'm pretty sure that properties is coming back such that you're not getting the 10.0D property, probably because of this.

 

Anyway, you should simply put System.out.println() statements in your code at key points in each class and print out the value of what is being processed in the code.  You should quickly see that you're getting either 0.0D or null back at some point when you don't expect it.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

I'm not entirely sure that's the problem because even when I do it like this the entity still dies instantly.

 

 

public class EntityBlockling extends EntityTameable {

 

public BlocklingStats properties = BlocklingStats.get(this);

public int level = properties.getLevel();

public double maxHealth = 10.0D;

 

public EntityBlockling(World world) {

 

super(world);

System.out.println(maxHealth);

this.setSize(0.91F, 0.91F);

this.getNavigator().setAvoidsWater(true);

this.getNavigator().setCanSwim(false);

this.tasks.addTask(0, new EntityAIAttackOnCollide(this, 1.0D, true));

this.tasks.addTask(1, new EntityAIWatchClosest(this, EntityPlayer.class, 16.0F));

        this.tasks.addTask(2, new EntityAIFollowOwner(this, 1.0D, 8.0F, 5.0F));

        this.tasks.addTask(3, this.aiSit);

        this.tasks.addTask(4, new EntityAIAvoidEntity(this, EntityPlayer.class, 16.0F, 1.5D, 1.5D));

        this.tasks.addTask(5, new EntityAIWander(this, 1.0D));

        this.targetTasks.addTask(0, new EntityAIOwnerHurtByTarget(this));

        this.targetTasks.addTask(1, new EntityAIOwnerHurtTarget(this));

        this.targetTasks.addTask(2, new EntityAIAttackOnCollide(this, 1.0D, true));

        this.setTamed(false);

       

}

 

protected void applyEntityAttributes() {

 

super.applyEntityAttributes();

 

this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth);

this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);

this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);

    this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D);

 

}

 

public boolean interact(EntityPlayer par1EntityPlayer)

    {

        ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem();

       

        if (itemstack != null && itemstack.getItem() == Item.getItemFromBlock(Blocks.red_flower))

        {

            if (!par1EntityPlayer.capabilities.isCreativeMode)

            {

                --itemstack.stackSize;

            }

 

            if (itemstack.stackSize <= 0)

            {

                par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, (ItemStack)null);

            }

 

            if (par1EntityPlayer.getCommandSenderName().equalsIgnoreCase(this.getOwnerName()) && !this.worldObj.isRemote)

            {

                this.aiSit.setSitting(!this.isSitting());

                this.isJumping = false;

                this.setPathToEntity((PathEntity)null);

                this.setTarget((Entity)null);

                this.setAttackTarget((EntityLivingBase)null);

                FMLClientHandler.instance().getClient().ingameGUI.getChatGUI().printChatMessage(new ChatComponentText("XP: " + Integer.toString(properties.getXP()) + "/" + properties.getRequiredXP() + " | " + "Level: " + properties.getLevel() + " | " + "Health: " + (int)this.getHealth() + "/" + maxHealth));

            }

           

            if (!this.worldObj.isRemote && !this.isTamed())

            {

                if (this.rand.nextInt(3) == 0)

                {

                    this.setTamed(true);

                    this.setPathToEntity((PathEntity)null);

                    this.setAttackTarget((EntityLivingBase)null);

                    this.setOwner(par1EntityPlayer.getCommandSenderName());

                    this.playTameEffect(true);

                    this.aiSit.setSitting(!this.isSitting());

                    this.worldObj.setEntityState(this, (byte)7);

                }

                else

                {

                    this.playTameEffect(false);

                    this.worldObj.setEntityState(this, (byte)6);

                }

            }

 

            return true;

        }

 

        return super.interact(par1EntityPlayer);

    }

 

public boolean attackEntityAsMob(Entity par1Entity) {

 

properties.addXP(50);

 

        return par1Entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue());

       

}

 

@SideOnly(Side.CLIENT)

    public int getLevel() {

 

        return properties.getLevel();

       

    }

 

@Override

public EntityAgeable createChild(EntityAgeable var1) {

 

return null;

 

}

 

public boolean isAIEnabled() {

 

return true;

 

}

 

}

 

 

Posted

You don't understand, at the point where you have this code:

public BlocklingStats properties = BlocklingStats.get(this);

 

The "this" that you're passing hasn't even been constructed yet.  You're trying to get properties for an entity that doesn't exist yet.

 

So all that stuff should be moved into your constructor.  Maybe something more like:

public class EntityBlockling extends EntityTameable {
   
   public BlocklingStats properties ;
   public int level;
   public double maxHealth = 10.0D;
   
   public EntityBlockling(World world) {
      
      super(world);

      properties = BlocklingStats.get(this); // <-- now the "this" should properly exist
      level = properties.getLevel();

      System.out.println("Constructing EntityBlockling");
      System.out.println("maxHealth field = "+maxHealth);
      System.out.println("properties.getMaxHeath() ="+properties.getMaxHealth());  // <-- add more debugging statements
      this.setSize(0.91F, 0.91F);

 

Now I'm not sure the above will fully fix your problem, but you should do it.  I think we also need to see what is happening in the applyEntityAttributes() method.  Add debug statement like this:

 protected void applyEntityAttributes() {

      super.applyEntityAttributes();
      
      System.out.println("Applying entity attributes");
      System.out.println("Before setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());
      this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth);   
      System.out.println("After setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());
      this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);
      this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);
       this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D);
      
   }

 

Run the code with the debug statements I added above and post the console output here.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Sorry I misunderstood before, changed it up, thanks. Here is the console after doing what you said.

 

Applying entity attributes

Before setting, maxHealth attribute = 20.0

After setting, maxHealth attribute = 0.0

Applying entity attributes

Before setting, maxHealth attribute = 20.0

After setting, maxHealth attribute = 0.0

Posted

Okay, so you can see that it is actually setting max health to 0 at point where you're setting the attribute.

 

Can you add debug statement so we can confirm that maxHealth is actually 0 at that point:

protected void applyEntityAttributes() {

 

      super.applyEntityAttributes();

     

      System.out.println("Applying entity attributes");

      System.out.println("maxHealth field ="+maxHealth);

      System.out.println("Before setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());

      this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth); 

      System.out.println("After setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());

      this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);

      this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);

      this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D);

     

  }

 

Run it again and post the console output here.  Please include the console output related to the constructor println statements I asked you to add earlier.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Okay, I have added the extra println() and here is the console output in the order it comes out.

 

Applying entity attributes

maxHealth field =0.0

Before setting, maxHealth attribute = 20.0

After setting, maxHealth attribute = 0.0

Constructing EntityBlockling

maxHealth field = 10.0

properties.getMaxHeath() =10.0

Posted

Okay, so it is obvious that the problem is that your maxHealth field is set to 0 at the point you're setting the attribute.

 

You just need to figure out why.  Can you post the full code for your class now since you've been editing it a bit?

 

In the worst case, instead of using a field, you could just set the attribute directly to the value you want, but it would be good to understand why this is happening.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Yeah, I pretty much have to use a field as I will be changing it depending on the entities level. Here is the whole entity class:

 

 

public class EntityBlockling extends EntityTameable {

 

public BlocklingStats properties;

public int level;

public double maxHealth;

 

public EntityBlockling(World world) {

 

super(world);

 

properties = BlocklingStats.get(this);

level = properties.getLevel();

maxHealth = properties.getMaxHealth();

 

System.out.println("Constructing EntityBlockling");

System.out.println("maxHealth field = "+maxHealth);

      System.out.println("properties.getMaxHeath() =" + properties.getMaxHealth());

 

this.setSize(0.91F, 0.91F);

this.getNavigator().setAvoidsWater(true);

this.getNavigator().setCanSwim(false);

this.tasks.addTask(0, new EntityAIAttackOnCollide(this, 1.0D, true));

this.tasks.addTask(1, new EntityAIWatchClosest(this, EntityPlayer.class, 16.0F));

        this.tasks.addTask(2, new EntityAIFollowOwner(this, 1.0D, 8.0F, 5.0F));

        this.tasks.addTask(3, this.aiSit);

        this.tasks.addTask(4, new EntityAIAvoidEntity(this, EntityPlayer.class, 16.0F, 1.5D, 1.5D));

        this.tasks.addTask(5, new EntityAIWander(this, 1.0D));

        this.targetTasks.addTask(0, new EntityAIOwnerHurtByTarget(this));

        this.targetTasks.addTask(1, new EntityAIOwnerHurtTarget(this));

        this.targetTasks.addTask(2, new EntityAIAttackOnCollide(this, 1.0D, true));

        this.setTamed(false);

       

}

 

protected void applyEntityAttributes() {

 

super.applyEntityAttributes();

 

System.out.println("Applying entity attributes");

System.out.println("maxHealth field =" + maxHealth);

System.out.println("Before setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());

this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth); 

System.out.println("After setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());

this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);

this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);

this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D);

 

}

 

public boolean interact(EntityPlayer par1EntityPlayer)

    {

        ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem();

       

        if (itemstack != null && itemstack.getItem() == Item.getItemFromBlock(Blocks.red_flower))

        {

            if (!par1EntityPlayer.capabilities.isCreativeMode)

            {

                --itemstack.stackSize;

            }

 

            if (itemstack.stackSize <= 0)

            {

                par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, (ItemStack)null);

            }

 

            if (par1EntityPlayer.getCommandSenderName().equalsIgnoreCase(this.getOwnerName()) && !this.worldObj.isRemote)

            {

                this.aiSit.setSitting(!this.isSitting());

                this.isJumping = false;

                this.setPathToEntity((PathEntity)null);

                this.setTarget((Entity)null);

                this.setAttackTarget((EntityLivingBase)null);

                FMLClientHandler.instance().getClient().ingameGUI.getChatGUI().printChatMessage(new ChatComponentText("XP: " + Integer.toString(properties.getXP()) + "/" + properties.getRequiredXP() + " | " + "Level: " + properties.getLevel() + " | " + "Health: " + (int)this.getHealth() + "/" + maxHealth));

            }

           

            if (!this.worldObj.isRemote && !this.isTamed())

            {

                if (this.rand.nextInt(3) == 0)

                {

                    this.setTamed(true);

                    this.setPathToEntity((PathEntity)null);

                    this.setAttackTarget((EntityLivingBase)null);

                    this.setOwner(par1EntityPlayer.getCommandSenderName());

                    this.playTameEffect(true);

                    this.aiSit.setSitting(!this.isSitting());

                    this.worldObj.setEntityState(this, (byte)7);

                }

                else

                {

                    this.playTameEffect(false);

                    this.worldObj.setEntityState(this, (byte)6);

                }

            }

 

            return true;

        }

 

        return super.interact(par1EntityPlayer);

    }

 

public boolean attackEntityAsMob(Entity par1Entity) {

 

properties.addXP(10);

 

        return par1Entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue());

       

}

 

@SideOnly(Side.CLIENT)

    public int getLevel() {

 

        return properties.getLevel();

       

    }

 

@Override

public EntityAgeable createChild(EntityAgeable var1) {

 

return null;

 

}

 

public boolean isAIEnabled() {

 

return true;

 

}

 

}

 

 

 

Also here is the "properties" class:

 

 

public class BlocklingStats implements IExtendedEntityProperties {

 

public final static String EXT_PROP_NAME = "BlocklingXP";

 

public EntityBlockling blockling;

public int xp = 0;

public int level = 1;

public int requiredXP = 256;

public double maxHealth = 10.0D;

 

public BlocklingStats(EntityBlockling blockling) {

 

this.blockling = blockling;

 

}

 

public static final void register(EntityBlockling blockling) {

 

blockling.registerExtendedProperties(BlocklingStats.EXT_PROP_NAME, new BlocklingStats(blockling));

 

}

 

public static final BlocklingStats get(EntityBlockling entity) {

 

return (BlocklingStats) entity.getExtendedProperties(EXT_PROP_NAME);

 

}

 

@Override

public void saveNBTData(NBTTagCompound compound) {

 

compound.setInteger("xp", this.xp);

compound.setInteger("level", this.level);

compound.setInteger("requiredXP", this.requiredXP);

compound.setDouble("maxHealth", this.maxHealth);

 

}

 

@Override

public void loadNBTData(NBTTagCompound compound) {

 

this.xp = compound.getInteger("xp");

this.level = compound.getInteger("level");

this.requiredXP = compound.getInteger("requiredXP");

this.maxHealth = compound.getDouble("maxHealth");

 

}

 

@Override

public void init(Entity entity, World world) {

 

 

 

}

 

public void addXP(int addedXP) {

 

xp = xp + addedXP;

onLevelUp();

 

}

 

public void onLevelUp() {

 

if(xp >= requiredXP) {

 

this.xp = 0;

this.level++;

calculateRequiredXP();

 

}

 

}

 

public void calculateRequiredXP() {

 

this.requiredXP = level * level * 8 * (8 + level);

 

}

 

public int getXP() {

 

return xp;

 

}

 

public int getRequiredXP() {

 

return requiredXP;

 

}

 

public int getLevel() {

 

return level;

 

}

 

public double getMaxHealth() {

 

return maxHealth;

 

}

 

}

 

 

Posted

Okay, what I believe is happening is that your loadNBT is being called and overwriting your maxHealth value in the properties class.

 

Again, you can debug this stuff easily yourself if you put in console statements for every method.  When I'm coding I seriously put in a System.out.println in every method so I can follow the execution to confirm it is correct.  So please add statements in your properties class, in all of the constructor, the loadNBT, and the getMaxHealth methods.  You should be very easily able to figure out where the problem is if you check the values at every point.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Okay I will just try to figure this out because I just got it to a stage where it seemed to work but it required me being able to call the applyEntityAttributes() method again so I go register the new max health, but this just leads to a crash because the entity is already spawned so it says in the console "attributes already registered". Hopefully I will get to the bottom of this, but at the moment I don't think I can update the entities max health without registering the attributes again which doesn't work.

Posted

Okay I will just try to figure this out because I just got it to a stage where it seemed to work but it required me being able to call the applyEntityAttributes() method again so I go register the new max health, but this just leads to a crash because the entity is already spawned so it says in the console "attributes already registered". Hopefully I will get to the bottom of this, but at the moment I don't think I can update the entities max health without registering the attributes again which doesn't work.

 

I don't think you're thinking this through.  To fix a problem you need to "trace" the execution of the code.  Pretend you're the computer and execute your code.  And use println statements to help you.  Don't just experiment, that isn't the way to fix things.

 

In this case, are you sure that the maxHealth isn't being changed to 0 when the loadNBT happens?  Something in your code is changing maxHealth value to 0, and that is the only place in the code that changes that field.  So look at that.

 

Just make sure every line of code is doing what you expect by confirming with println.  It should only take you about 3 minutes to figure this out if you trace the execution to the point where maxHealth is being changed to 0.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

I figured out now why it wasn't working by adding println() statements like you said. Basically when the mob spawns the applyEntityAttributes() method is called before the constructor and I was initializing the maxHealth field in the constructor which meant it only happened after the attributes were applied so it now works. But I have one last problem, I cannot reapply entity attributes to a mob as I get the error mentioned before where it says "Attribute is already registered!" and the game crashes which makes sense. So I am wondering if there is a way around this. I know that the wolves are able to update their max health when they are tamed but there is no indication of the applyEntityAttributes() method being called again so I don't understand why their health updates but not mine. If anyone knows that would be great but if not I will just continue to try and figure it out.

Posted

If you look closely at your apply attributes method you are registering the attackDamage attribute in that method and you're also calling the super method which registers other attributes.  So if you called the apply attributes method again there would be an error.

 

So if you want to update attributes later, you should create different method called setAttributes() that doesn't include the lines that do registrations.  Or if you only want to update the max health then create an setMaxHealthAttribute() method that only does that:

   public void setMaxHealthAttribute(double parMaxHealth) 
{
      maxHealth = parMaxHealth;
      
      System.out.println("Setting maxHealth attribute");
     System.out.println("Before setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());
      this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(maxHealth);   
      System.out.println("After setting, maxHealth attribute = "+this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue());      
   }

 

Honestly, what I'm trying to teach you is to go through your code line by line and "trace" what would happen.  It should be very easy to see that if you get an error that says "already registered" and you go back to your code and see that you are in fact registering again, so fix it...

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

Okay, I have spent a good 3 hours sat doing what you said and I now fully understand and appreciate the importance of doing as much as you can yourself. I actually managed to solve it by myself and realised why it was happening and I can apply it to other situations. So I guess I should thank you for persevering with me (I could tell it was frustrating you a bit) and pushing to get the point across because it has and will benefit me greatly in the future :D

Posted

Okay, I have spent a good 3 hours sat doing what you said and I now fully understand and appreciate the importance of doing as much as you can yourself. I actually managed to solve it by myself and realised why it was happening and I can apply it to other situations. So I guess I should thank you for persevering with me (I could tell it was frustrating you a bit) and pushing to get the point across because it has and will benefit me greatly in the future :D

 

Awesome.  The reason I perservered with you is because I knew you were close and just needed the push.  Programming is about details and understanding every line of execution.  Printing to console can get you a long way to helping you trace the execution and detect what is going wrong.  With that skill alone you'll advance very quickly.

 

Cheers!

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

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

    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
  • Topics

×
×
  • Create New...

Important Information

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