Jump to content

Recommended Posts

Posted

I've extended EntityVillager and made a class with a few things that I will use in my mod. How to use the EntityRegistry and I want these to override vanilla mc villagers but only the vanilla careers and professions. Also, do I need to put in EntityVillager AI and my custom made AI or is this not needed?

Posted

Okay, so I've figured out everything above, however, my villagers don't work at all. They override regular villagers successfully and display the correct texture. That's it, they don't move or have any AI. They just gets hearts and endless stacks villages inside the same block. They don't die from lava, they don't even fall.

 

public class OverrideVillagers {
@SubscribeEvent
public void entityJoinedWorldEventHandler(EntityJoinWorldEvent event)
{
	if (event.getEntity().getClass() == EntityVillager.class && Config.overwriteOriginalVillagers)
	{
		doOverwriteVillager(event, (EntityVillager) event.getEntity());
	}
}

private void doOverwriteVillager(EntityJoinWorldEvent event, EntityVillager entity) 
{
	if (entity.getProfession() >= 0 && entity.getProfession() <= 4)
	{
		entity.setDead();
		EntityVillager entityVillager = new EntityVillager(event.getWorld());
		entityVillager.onInitialSpawn(event.getWorld().getDifficultyForLocation(new BlockPos(entity)), (IEntityLivingData)null);
		entityVillager.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, 0.0F, 0.0F);
		event.getWorld().spawnEntity(entityVillager);
		event.getWorld().setEntityState(entityVillager, (byte)12);
		entityVillager.setProfession(entity.getProfession()); 
		entityVillager.setGrowingAge(entity.getGrowingAge());
	}
}
}

public class IvVillager extends EntityVillager{

protected Village villageObj; 
public String name;
public int Gender;
    protected boolean isWillingToMate;
    protected int wealth;
    private MerchantRecipeList buyingList;
    private String lastBuyingPlayer;
    private int careerId;
    private int careerLevel;
    private boolean isLookingForHome;
    private boolean areAdditionalTasksSet;
    private final InventoryBasic villagerInventory;
    Random r = new Random();
    /** A multi-dimensional array mapping the various professions, careers and career levels that a Villager may offer */
protected String[] male_list = {"Bob", "Joseph", "Aaron", "Philp", "Adam", "Paul", "Donald", "Ryan", 
								"Mark", "Brian", "Robert", "Willam", "Harold", "Anthony", "Julius", 
								"Mathew", "Tyler", "Noah", "Patrick", "Caden", "Michael", "Jeffery",
								"James", "John", "Thomas", "Otto", "Bill", "Sheldon", "Leonard", 
								"Howard", "Carter", "Theodore", "Herbert"};
protected String[] female_list = {"Karen", "Lessie", "Kayla", "Brianna", "Isabella", "Elizabeth",
								  "Kira", "Jadzia", "Abigail", "Chloe", "Olivia", "Sophia", "Emily", 
								  "Charlotte", "Amelia", "Maria", "Daria", "Sarah", "Theodora",
								  "Tia", "Jennifer", "Anglica", "Denna", "Tasha", "Catherine", "Lily",
								  "Amy", "Penny", "Julina", "Audrey", "Avery"};


public IvVillager(World world, int professionId) {
	super(world, professionId);
    this.villagerInventory = new InventoryBasic("Items", false, ;
    this.setCanPickUpLoot(true);
    this.setProfession(professionId);
}
public InventoryBasic getVillagerInventory()
    {
        return this.villagerInventory;
    }

private void setAdditionalAItasks()
    {
        if (!this.areAdditionalTasksSet)
        {
            this.areAdditionalTasksSet = true;

            if (this.isChild())
            {
                this.tasks.addTask(8, new EntityAIPlay(this, 0.32D));
            }
            else if (this.getProfession() == 0)
            {
                this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D));
            }
        }
    }
 @Override
 public void writeEntityToNBT(NBTTagCompound compound)
    {
        super.writeEntityToNBT(compound);
        compound.setInteger("Profession", this.getProfession());
        compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
        compound.setInteger("Riches", this.wealth);
        compound.setInteger("Career", this.careerId);
        compound.setInteger("CareerLevel", this.careerLevel);
        compound.setBoolean("Willing", this.isWillingToMate);

        if (this.buyingList != null)
        {
            compound.setTag("Offers", this.buyingList.getRecipiesAsTags());
        }

        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.getVillagerInventory().getSizeInventory(); ++i)
        {
            ItemStack itemstack = this.villagerInventory.getStackInSlot(i);

            if (!itemstack.isEmpty())
            {
                nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound()));
            }
        }

        compound.setTag("Inventory", nbttaglist);
        if (compound.getInteger("Gender") != 1 || compound.getInteger("Gender") != 2)
        {
        	compound.setInteger("Gender", this.Gender);
        }
        if (this.getCustomNameTag() == null){
        	if (compound.getInteger("Gender") == 1){
        		this.setCustomNameTag(male_list[r.nextInt(male_list.length)]);
        	}
        if (compound.getInteger("Gender") == 2){
        			this.setCustomNameTag(female_list[r.nextInt(female_list.length)]);
        	}
        }
        
    }
 @Override
 public void readEntityFromNBT(NBTTagCompound compound){
	 super.writeEntityToNBT(compound);
	 this.name = this.getCustomNameTag();
	 this.Gender = compound.getInteger("Gender");
	 this.setProfession(compound.getInteger("Profession"));
        if (compound.hasKey("ProfessionName"))
        {
            net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
                net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
            if (p == null)
                p = net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
            this.setProfession(p);
        }
        this.wealth = compound.getInteger("Riches");
        this.careerId = compound.getInteger("Career");
        this.careerLevel = compound.getInteger("CareerLevel");
        this.isWillingToMate = compound.getBoolean("Willing");

        if (compound.hasKey("Offers", 10))
        {
            NBTTagCompound nbttagcompound = compound.getCompoundTag("Offers");
            this.buyingList = new MerchantRecipeList(nbttagcompound);
        }

        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            ItemStack itemstack = new ItemStack(nbttaglist.getCompoundTagAt(i));

            if (!itemstack.isEmpty())
            {
                this.villagerInventory.addItem(itemstack);
            }
        }

        this.setCanPickUpLoot(true);
        this.setAdditionalAItasks();

 }
 private void populateBuyingList()
    {
        if (this.careerId != 0 && this.careerLevel != 0)
        {
            ++this.careerLevel;
        }
        else
        {
            this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
            this.careerLevel = 1;
        }

        if (this.buyingList == null)
        {
            this.buyingList = new MerchantRecipeList();
        }

        int i = this.careerId - 1;
        int j = this.careerLevel - 1;
        java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);

        if (trades != null)
        {
            for (EntityVillager.ITradeList entityvillager$itradelist : trades)
            {
                entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
            }
        }
    }
 @Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
	BlockPos blockpos = new BlockPos(this);
	this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32);
        ItemStack itemstack = player.getHeldItem(hand);

        if (itemstack.getItem() == IvItems.thieving_nose && !player.capabilities.isCreativeMode && !this.isChild())
        {
        	itemstack.damageItem(1, player);
        	if (rand.nextInt(10) + 1 < 6){
        		
        	}
        	if (rand.nextInt(10) + 1 < 9 && rand.nextInt(10) + 1  > 5){
        		player.dropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), false);
        	}
        	if (rand.nextInt(10) + 1 < 10 && rand.nextInt(10) + 1  > {
        		player.dropItem(new ItemStack(Items.EMERALD, r.nextInt(6) + 3), false);
        	}
        	if (this.villageObj != null)
            {
        		this.villageObj.modifyPlayerReputation(player.getName(), -2);
            } 
            return true;
        }
        else if (!this.holdingSpawnEggOfClass(itemstack, this.getClass()) && this.isEntityAlive() && !this.isTrading() && !this.isChild())
        {
            if (this.buyingList == null)
            {
                this.populateBuyingList();
            }

            if (hand == EnumHand.MAIN_HAND)
            {
                player.addStat(StatList.TALKED_TO_VILLAGER);
            }

            if (!this.world.isRemote && !this.buyingList.isEmpty())
            {
                this.setCustomer(player);
                player.displayVillagerTradeGui(this);
            }
            else if (this.buyingList.isEmpty())
            {
                return super.processInteract(player, hand);
            }

            return true;
        }
        else
        {
            return super.processInteract(player, hand);
        }
    }

}

public class CommonProxy {

@EventHandler
    public void preInit(FMLPreInitializationEvent e) {
	ResourceLocation resourceLocation1 = new ResourceLocation("minecraft", "EntityVillager");
	EntityRegistry.registerModEntity(resourceLocation1, IvVillager.class, "IvVillager", 0, Iv.instance, 32, 1, true);

}
@EventHandler
    public void init(FMLInitializationEvent e) {
}
    @EventHandler
    public void postInit(FMLPostInitializationEvent e) {

    }
}

Posted

Show your entity class. You fucked something up there, not in the replacement.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Reposting entity class + the AI I give to EntityVillagers and the IvVillager.

 

public class IvVillager extends EntityVillager{

protected Village villageObj; 
public String name;
public int Gender;
    protected boolean isWillingToMate;
    protected int wealth;
    private MerchantRecipeList buyingList;
    private String lastBuyingPlayer;
    private int careerId;
    private int careerLevel;
    private boolean isLookingForHome;
    private boolean areAdditionalTasksSet;
    private final InventoryBasic villagerInventory;
    Random r = new Random();
    /** A multi-dimensional array mapping the various professions, careers and career levels that a Villager may offer */
protected String[] male_list = {"Bob", "Joseph", "Aaron", "Philp", "Adam", "Paul", "Donald", "Ryan", 
								"Mark", "Brian", "Robert", "Willam", "Harold", "Anthony", "Julius", 
								"Mathew", "Tyler", "Noah", "Patrick", "Caden", "Michael", "Jeffery",
								"James", "John", "Thomas", "Otto", "Bill", "Sheldon", "Leonard", 
								"Howard", "Carter", "Theodore", "Herbert"};
protected String[] female_list = {"Karen", "Lessie", "Kayla", "Brianna", "Isabella", "Elizabeth",
								  "Kira", "Jadzia", "Abigail", "Chloe", "Olivia", "Sophia", "Emily", 
								  "Charlotte", "Amelia", "Maria", "Daria", "Sarah", "Theodora",
								  "Tia", "Jennifer", "Anglica", "Denna", "Tasha", "Catherine", "Lily",
								  "Amy", "Penny", "Julina", "Audrey", "Avery"};


public IvVillager(World world, int professionId) {
	super(world, professionId);
    this.villagerInventory = new InventoryBasic("Items", false, ;
    this.setCanPickUpLoot(true);
    this.setProfession(professionId);
}
public InventoryBasic getVillagerInventory()
    {
        return this.villagerInventory;
    }

private void setAdditionalAItasks()
    {
        if (!this.areAdditionalTasksSet)
        {
            this.areAdditionalTasksSet = true;

            if (this.isChild())
            {
                this.tasks.addTask(8, new EntityAIPlay(this, 0.32D));
            }
            else if (this.getProfession() == 0)
            {
                this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D));
            }
        }
    }
 @Override
 public void writeEntityToNBT(NBTTagCompound compound)
    {
        super.writeEntityToNBT(compound);
        compound.setInteger("Profession", this.getProfession());
        compound.setString("ProfessionName", this.getProfessionForge().getRegistryName().toString());
        compound.setInteger("Riches", this.wealth);
        compound.setInteger("Career", this.careerId);
        compound.setInteger("CareerLevel", this.careerLevel);
        compound.setBoolean("Willing", this.isWillingToMate);

        if (this.buyingList != null)
        {
            compound.setTag("Offers", this.buyingList.getRecipiesAsTags());
        }

        NBTTagList nbttaglist = new NBTTagList();

        for (int i = 0; i < this.getVillagerInventory().getSizeInventory(); ++i)
        {
            ItemStack itemstack = this.villagerInventory.getStackInSlot(i);

            if (!itemstack.isEmpty())
            {
                nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound()));
            }
        }

        compound.setTag("Inventory", nbttaglist);
        if (compound.getInteger("Gender") != 1 || compound.getInteger("Gender") != 2)
        {
        	compound.setInteger("Gender", this.Gender);
        }
        if (this.getCustomNameTag() == null){
        	if (compound.getInteger("Gender") == 1){
        		this.setCustomNameTag(male_list[r.nextInt(male_list.length)]);
        	}
        if (compound.getInteger("Gender") == 2){
        			this.setCustomNameTag(female_list[r.nextInt(female_list.length)]);
        	}
        }
        
    }
 @Override
 public void readEntityFromNBT(NBTTagCompound compound){
	 super.writeEntityToNBT(compound);
	 this.name = this.getCustomNameTag();
	 this.Gender = compound.getInteger("Gender");
	 this.setProfession(compound.getInteger("Profession"));
        if (compound.hasKey("ProfessionName"))
        {
            net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession p =
                net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation(compound.getString("ProfessionName")));
            if (p == null)
                p = net.minecraftforge.fml.common.registry.VillagerRegistry.instance().getRegistry().getValue(new net.minecraft.util.ResourceLocation("minecraft:farmer"));
            this.setProfession(p);
        }
        this.wealth = compound.getInteger("Riches");
        this.careerId = compound.getInteger("Career");
        this.careerLevel = compound.getInteger("CareerLevel");
        this.isWillingToMate = compound.getBoolean("Willing");

        if (compound.hasKey("Offers", 10))
        {
            NBTTagCompound nbttagcompound = compound.getCompoundTag("Offers");
            this.buyingList = new MerchantRecipeList(nbttagcompound);
        }

        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            ItemStack itemstack = new ItemStack(nbttaglist.getCompoundTagAt(i));

            if (!itemstack.isEmpty())
            {
                this.villagerInventory.addItem(itemstack);
            }
        }

        this.setCanPickUpLoot(true);
        this.setAdditionalAItasks();

 }
 private void populateBuyingList()
    {
        if (this.careerId != 0 && this.careerLevel != 0)
        {
            ++this.careerLevel;
        }
        else
        {
            this.careerId = this.getProfessionForge().getRandomCareer(this.rand) + 1;
            this.careerLevel = 1;
        }

        if (this.buyingList == null)
        {
            this.buyingList = new MerchantRecipeList();
        }

        int i = this.careerId - 1;
        int j = this.careerLevel - 1;
        java.util.List<EntityVillager.ITradeList> trades = this.getProfessionForge().getCareer(i).getTrades(j);

        if (trades != null)
        {
            for (EntityVillager.ITradeList entityvillager$itradelist : trades)
            {
                entityvillager$itradelist.addMerchantRecipe(this, this.buyingList, this.rand);
            }
        }
    }
 @Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
	BlockPos blockpos = new BlockPos(this);
	this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32);
        ItemStack itemstack = player.getHeldItem(hand);

        if (itemstack.getItem() == IvItems.thieving_nose && !player.capabilities.isCreativeMode && !this.isChild())
        {
        	itemstack.damageItem(1, player);
        	if (rand.nextInt(10) + 1 < 6){
        		
        	}
        	if (rand.nextInt(10) + 1 < 9 && rand.nextInt(10) + 1  > 5){
        		player.dropItem(new ItemStack(Items.EMERALD, r.nextInt(2) + 1), false);
        	}
        	if (rand.nextInt(10) + 1 < 10 && rand.nextInt(10) + 1  > {
        		player.dropItem(new ItemStack(Items.EMERALD, r.nextInt(6) + 3), false);
        	}
        	if (this.villageObj != null)
            {
        		this.villageObj.modifyPlayerReputation(player.getName(), -2);
            } 
            return true;
        }
        else if (!this.holdingSpawnEggOfClass(itemstack, this.getClass()) && this.isEntityAlive() && !this.isTrading() && !this.isChild())
        {
            if (this.buyingList == null)
            {
                this.populateBuyingList();
            }

            if (hand == EnumHand.MAIN_HAND)
            {
                player.addStat(StatList.TALKED_TO_VILLAGER);
            }

            if (!this.world.isRemote && !this.buyingList.isEmpty())
            {
                this.setCustomer(player);
                player.displayVillagerTradeGui(this);
            }
            else if (this.buyingList.isEmpty())
            {
                return super.processInteract(player, hand);
            }

            return true;
        }
        else
        {
            return super.processInteract(player, hand);
        }
    }

}

public class ChangeVilMateAI {

@SubscribeEvent
public void entityVillagerAIOverride(LivingSpawnEvent event) {
     if (event.getEntity() != null){
	    if (event.getEntity() instanceof EntityVillager) {
	          EntityVillager villager = (EntityVillager) event.getEntity();
	          villager.tasks.addTask(3, new VilsPerDoor(villager));
	     }
	    else if (event.getEntity() instanceof IvVillager) {
	          IvVillager villager = (IvVillager) event.getEntity();
	          villager.tasks.addTask(3, new IvVilsPerDoor(villager));
	     }
	}
}
}

Posted

I'm at a loss.

You call super for the methods you've overridden and you haven't overridden onUpdate...

 

Nope, no idea.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

In your event you are not creating a new instance of your EntityVillager, but a vanilla one. And then you add it to the world which fires the on EntityJoinedWorldEvent, this hangs the server thread and nothing gets updated.

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.

Posted

Thank, however my code crashes on

 

@Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
	BlockPos blockpos = new BlockPos(this);
	this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32); //Here
        ItemStack itemstack = player.getHeldItem(hand);

Posted

Thank, however my code crashes on

 

@Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
	BlockPos blockpos = new BlockPos(this);
	this.villageObj = this.world.getVillageCollection().getNearestVillage(blockpos, 32); //Here
        ItemStack itemstack = player.getHeldItem(hand);

Probably a NullPointerException use your debugger to figure it out, or use printlns to identify it.

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.

Posted

Whenever I spawn in a villager and it gets overridden, I get this error

 

[FML]: A severe problem occurred during the spawning of an entity at ( 940.5,4.0, -362.5)
java.lang.NoSuchMethodException: orangeVillager61.ImprovedVillagers.Entities.IvVillager.<init>(net.minecraft.world.World)
at java.lang.Class.getConstructor0(Unknown Source) ~[?:1.8.0_111]
at java.lang.Class.getConstructor(Unknown Source) ~[?:1.8.0_111]
at net.minecraftforge.fml.common.network.internal.EntitySpawnHandler.spawnEntity(EntitySpawnHandler.java:96) [EntitySpawnHandler.class:?]
at net.minecraftforge.fml.common.network.internal.EntitySpawnHandler.process(EntitySpawnHandler.java:73) [EntitySpawnHandler.class:?]
at net.minecraftforge.fml.common.network.internal.EntitySpawnHandler.access$000(EntitySpawnHandler.java:48) [EntitySpawnHandler.class:?]
at net.minecraftforge.fml.common.network.internal.EntitySpawnHandler$1.run(EntitySpawnHandler.java:63) [EntitySpawnHandler$1.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_111]
at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_111]
at net.minecraft.util.Util.runTask(Util.java:26) [util.class:?]
at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1107) [Minecraft.class:?]
at net.minecraft.client.Minecraft.run(Minecraft.java:405) [Minecraft.class:?]
at net.minecraft.client.main.Main.main(Main.java:118) [Main.class:?]

 

I think it may be related to my nullpointer issue.

Posted

Entity classes must have a public constructor with a single

World

argument.

 

Yep

 

public IvVillager(World world, int professionId) {
	super(world, professionId);
    this.villagerInventory = new InventoryBasic("Items", false, ;
    this.setCanPickUpLoot(true);
}

Posted

That is a

World

and an

int

. Not a single

World

argument.

 

Alright, but I've still be getting this crash,

 

java.lang.NullPointerException: Unexpected error
at orangeVillager61.ImprovedVillagers.Entities.IvVillager.processInteract(IvVillager.java:223)
at net.minecraft.entity.EntityLiving.processInitialInteract(EntityLiving.java:1337)
at net.minecraft.entity.player.EntityPlayer.interactOn(EntityPlayer.java:1273)
at net.minecraft.client.multiplayer.PlayerControllerMP.interactWithEntity(PlayerControllerMP.java:573)
at net.minecraft.client.Minecraft.rightClickMouse(Minecraft.java:1592)
at net.minecraft.client.Minecraft.processKeyBinds(Minecraft.java:2274)
at net.minecraft.client.Minecraft.runTickKeyboard(Minecraft.java:2051)
at net.minecraft.client.Minecraft.runTick(Minecraft.java:1839)
at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1117)

 

@Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
        ItemStack itemstack = player.getHeldItem(hand);
        BlockPos blockpos = new BlockPos(this);
	this.ivillageObj = this.getWorld().getVillageCollection().getNearestVillage(blockpos, 32); // Crashing here.
        if (itemstack.getItem() == IvItems.thieving_nose && !player.capabilities.isCreativeMode && !this.isChild())
        {
...

Posted

So this would work?

 

@SideOnly(Side.SERVER)
 public void initServerVars(){
		BlockPos blockpos = new BlockPos(this);
		this.ivillageObj = this.getWorld().getVillageCollection().getNearestVillage(blockpos, 32);
 }@Override
 public boolean processInteract(EntityPlayer player, EnumHand hand){
        ItemStack itemstack = player.getHeldItem(hand);
        this.initServerVars();
        if (itemstack.getItem() == IvItems.thieving_nose && !player.capabilities.isCreativeMode && !this.isChild())
        {...

 

Posted

Alright, so I'm trying to get MC to give every villager a name from a list I made, however this is not working.

 

t
protected String[] male_list = {"Bob", "Joseph", "Aaron", "Philp", "Adam", "Paul", "Donald", "Ryan", 
								"Mark", "Brian", "Robert", "Willam", "Harold", "Anthony", "Julius", 
								"Mathew", "Tyler", "Noah", "Patrick", "Caden", "Michael", "Jeffery",
								"James", "John", "Thomas", "Otto", "Bill", "Sheldon", "Leonard", 
								"Howard", "Carter", "Theodore", "Herbert"};
protected String[] female_list = {"Karen", "Lessie", "Kayla", "Brianna", "Isabella", "Elizabeth",
								  "Kira", "Jadzia", "Abigail", "Chloe", "Olivia", "Sophia", "Emily", 
								  "Charlotte", "Amelia", "Maria", "Daria", "Sarah", "Theodora",
								  "Tia", "Jennifer", "Anglica", "Denna", "Tasha", "Catherine", "Lily",
								  "Amy", "Penny", "Julina", "Audrey", "Avery"};
@Override
public void readEntityFromNBT(NBTTagCompound compound){
this.name = this.getCustomNameTag();
	 System.out.println(this.name);
	 this.Gender = compound.getInteger("Gender");
	    if (this.Gender != 1 || this.Gender != 2){
	    	this.Gender = r.nextInt(2) + 1;
	    }
	 if (this.name == null){
		    if (this.Gender == 1){
	        	this.name = male_list[r.nextInt(male_list.length)];
	        }
	        else if (this.Gender == 2){
	        	this.name = female_list[r.nextInt(female_list.length)];
		    }
		    else if (this.Gender != 1 && this.Gender != 2){
		        this.name = "None";
		        System.out.println("Villager Gender Error");
		    }
	    }
}

Posted

Use capabilities.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Storing the information and syncing with the client.

 

getEntityData() is not a good use for what you are doing.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Storing the information and syncing with the client.

 

getEntityData() is not a good use for what you are doing.

 

So how to have a capability use two variables? Since I tried using two of them and it crashed.

 

public class VillagerStoragesName implements IStorage<IVillagerStorage>

{

 @Override

 public NBTBase writeNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side)

 {
 return new NBTTagString(instance.getName());
 }



 public void readNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side, NBTBase nbt)

 {
 instance.setName(((NBTPrimitive) nbt).toString());

 }
}

public class VillagerStoragesGender implements IStorage<IVillagerStorage>

{

 @Override

 public NBTBase writeNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side)

 {
 return new NBTTagInt(instance.getGender());
 }



 public void readNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side, NBTBase nbt)

 {

 instance.setGender(((NBTPrimitive) nbt).getInt());
 }
}

Posted

and it crashed.

 

1ie46g.jpg

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

and it crashed.

 

 

The crash said that I can't register two capabilities with the almost the same thing.

 

@EventHandler
    public void preInit(FMLPreInitializationEvent e) {
	MinecraftForge.EVENT_BUS.register(new CapabilityHandler());
	CapabilityManager.INSTANCE.register(IVillagerStorage.class, new VillagerStoragesGender(), VillagerStorage.class);
	CapabilityManager.INSTANCE.register(IVillagerStorage.class, new VillagerStoragesName(), VillagerStorage.class);
}
}

Posted

Don't register the same capability twice. Your storage needs to save everything from your capability. Don't create a separate storage for every piece of data.

Okay, but how would I merge the two since writeNbt can return only one thing.

Posted

NBTTagCompound

for example.

So this would work.

@Override

 public NBTBase writeNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side)

 {
	NBTTagCompound compound = new NBTTagCompound();
	compound.setInteger("Gender", instance.getGender());
	compound.setString("Name", instance.getName());
	return new NBTTagString(instance.getName());
 }



 public void readNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side, NBTBase nbt)

 {
 instance.setName(((NBTPrimitive) nbt).toString());
 instance.setGender(((NBTPrimitive) nbt).getInt());
 }

Posted

No, that wouldn't work.

 

In

writeNBT

, you create an

NBTTagCompound

and store the data in it; but you then return a completely unrelated

NBTTagString

and do nothing with the

NBTTagCompound

. You need to return the

NBTTagCompound

.

 

In

readNBT

, you assume that the

NBTBase

argument is an instance of

NBTPrimitive

(it won't be if

writeNBT

returns an

NBTTagCompound

) that somehow contains both the name and the gender at the same time. You need to cast the argument to

NBTTagCompound

and retrieve the individual values from it using

NBTTagCompound#getString

and

NBTTagCompound#getInteger

.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Posted

No, that wouldn't work.

 

In

writeNBT

, you create an

NBTTagCompound

and store the data in it; but you then return a completely unrelated

NBTTagString

and do nothing with the

NBTTagCompound

. You need to return the

NBTTagCompound

.

 

In

readNBT

, you assume that the

NBTBase

argument is an instance of

NBTPrimitive

(it won't be if

writeNBT

returns an

NBTTagCompound

) that somehow contains both the name and the gender at the same time. You need to cast the argument to

NBTTagCompound

and retrieve the individual values from it using

NBTTagCompound#getString

and

NBTTagCompound#getInteger

.

Ah, okay so this would work.

 

@Override

 public NBTBase writeNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side)

 {
	NBTTagCompound compound = new NBTTagCompound();
	compound.setInteger("Gender", instance.getGender());
	compound.setString("Name", instance.getName());
	return compound;
 }



 public void readNBT(Capability<IVillagerStorage> capability, IVillagerStorage instance, EnumFacing side, NBTBase nbt)

 {

 instance.setName(((NBTTagCompound) nbt).getString("Name"));
 instance.setGender(((NBTTagCompound) nbt).getInteger("Gender"));
 }

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

    • So me and a couple of friends are playing with a shitpost mod pack and one of the mods in the pack is corail tombstone and for some reason there is a problem with it, where on death to fire the player will get kicked out of the server and the tombstone will not spawn basically deleting an entire inventory, it doesn't matter what type of fire it is, whether it's from vanilla fire/lava, or from modded fire like ice&fire/lycanites and it's common enough to where everyone on the server has experienced at least once or twice and it doesn't give any crash log. a solution to this would be much appreciated thank you!
    • 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.