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

[1.8]Generating Mob Spawners


JoieNL
 Share

Recommended Posts

Hello fellow modders,

 

Lately I found myself at an impasse when trying to generate mob spawners in my custom structure. The generation of the spawner itself is not the problem, but rather the specifics of the spawner and the mob spawned. For the spawner itself, I want to be able to set the initial spawn delay, spawned mob, number of mobs spawned each time, spawn range, minimum and maximum delay between spawns, maximum nearby entities and required player distance to the spawner. For the spawned mob, I would like to add equipment (i.e. a weapon and armour) and maybe give it some potion effects. Now, I know how to do the latter if I have an instance of an EntityLiving, but I cannot figure out how to get said instance (and then set it) for a spawner. Please let me know if what I want is even possible with Minecraft's default classes, and, if it's not, how I would go about making custom spawner classes. Thanks in advance!

 

PS: Here is my code for reference:

Spoiler

public static void generateWaterTower(int x, int y, int z, Random random, World world) {
	BlockPos origin = new BlockPos(x, getTopBlock(new BlockPos(x, y, z), world).getY(), z);
	(...)
	world.setBlockState(origin.add(11, 1, 11), Blocks.mob_spawner.getDefaultState());
	TileEntityMobSpawner spawner = (TileEntityMobSpawner) world.getTileEntity(origin.add(11, 1, 11));
	(...)
}

 

 

Link to comment
Share on other sites

Quote

Why are you using 1.8?

I am using 1.8 mostly because I cannot stand the combat system introduced in 1.9. Either way, I do not plan to update.

 

Quote

The MobSpawnerBaseLogic of the spawner lets you modify what should be spawned.

Right, but it only allows you to pass a String (that is, the mobID), which means you can only set what kind of creature you want it to spawn, not the specifics of both the spawner and the spawned creature.

Link to comment
Share on other sites

17 minutes ago, JoieNL said:

I am using 1.8 mostly because I cannot stand the combat system introduced in 1.9. Either way, I do not plan to update.

At least use 1.8.9 then. And 1.8.x is not going to be supported much longer on this forum, just FYI.

 

MobSpawnerBaseLogic::getRandomEntity returns the WeightedRandomMinecart (that's what you get for using an outdated version, stupid names) instance, which stores the information about the entity to be spawned.

Link to comment
Share on other sites

14 minutes ago, diesieben07 said:

At least use 1.8.9 then. And 1.8.x is not going to be supported much longer on this forum, just FYI.

Well, I am using 1.8.9, I just figured the the topic pertained to the entirety of 1.8.

 

1 hour ago, diesieben07 said:

MobSpawnerBaseLogic::getRandomEntity returns the WeightedRandomMinecart (that's what you get for using an outdated version, stupid names) instance, which stores the information about the entity to be spawned.

So by configuring the NBT of this WeightedRandomMinecart instance I can apply armour and potion effects to the spawned entity? Alright, but then how about the properties of the spawner itself?

Link to comment
Share on other sites

I have figured out how to edit the mob spawner's characteristics through the use of reflection. Now, I have been trying to configure the spawned entity's characteristics by using reflection to edit the NBTTagCompound "nbtData" in the inner class WeightedRandomMinecart in MobSpawnerBaseLogic. After many fruitless attempts, I just don't know what to try anymore. How do I go about setting "nbtData" while using the right arguments in Field::set(Object obj, Object value) and how do I convert (an array of) ItemStacks to NBT that MobSpawnerBaseLogic can read?

Link to comment
Share on other sites

1 minute ago, diesieben07 said:

This does not make sense, the NBT is for an entity, not for ItemStacks.

Perhaps I should have been a bit more elaborate. The array of ItemStacks would be the equipment the Entity must have.

 

As for my current code...

MobSpawnerExtendedLogic.class:

Spoiler

public static void setNBT(Object object) {
    NBTTagList tagList = new NBTTagList();
    ItemStack[] equipment = new ItemStack[] {new ItemStack(ModItems.osmiumSword), new ItemStack(ModItems.osmiumBoots), new ItemStack(ModItems.osmiumLeggings), new ItemStack(ModItems.osmiumChestplate), new ItemStack(ModItems.osmiumHelmet)};
    for (ItemStack stack : equipment) {
        NBTTagCompound nbttagcompound = new NBTTagCompound();
        stack.writeToNBT(nbttagcompound);
        tagList.appendTag(nbttagcompound);
    }
    NBTTagCompound tag = new NBTTagCompound();
    tag.setTag("Equipment", tagList);
    NBTTagCompound tagCompound = new NBTTagCompound();
    tagCompound.setTag("Properties", tag);
    try {
        Field field = MobSpawnerBaseLogic.WeightedRandomMinecart.class.getDeclaredField("nbtData");
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        Field randomEntity = MobSpawnerBaseLogic.class.getDeclaredField("randomEntity");
        randomEntity.setAccessible(true);
        Object obj = randomEntity.get(object);
        field.set(obj, tagCompound);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

 

 

WaterTower.class:

world.setBlockState(origin.add(11, 1, 11), Blocks.mob_spawner.getDefaultState());
TileEntityMobSpawner spawner = (TileEntityMobSpawner) world.getTileEntity(origin.add(11, 1, 11));
setNBT(spawner.getSpawnerBaseLogic());

 

Link to comment
Share on other sites

  • 2 weeks later...

Well, after a lot of trial and error, I've figured things out. I am now able to configure the specifics of a generated mob spawner, as well as the specifics of the entitiy it should spawn. All these values are contained within the MobSpawnerBaseLogic class. I created a class, MobSpawnerExtendedLogic, that extends that class in which I created methods for modifying all these values. The methods I created use Java's reflection system. The methods are static because I have to use them in a static context. The argument to pass in as spawnerLogic should be the logic of the spawner you are trying to modify. For a spawner positioned at BlockPos pos in World world, you would pass ((TileEntityMobSpawner) world.getTileEntity(pos))).getSpawnerBaseLogic(). Here are my MobSpawnerExtendedLogic class and an implementation of the methods within it:

 

MobSpawnerExtendedLogic.class:

Spoiler

public abstract class MobSpawnerExtendedLogic extends MobSpawnerBaseLogic {
    /**
     *
     * @param mobID The {@code String} that represents the Entity the spawner should spawn.
     * @param initialSpawnDelay The delay (in ticks) between when the player first enters the spawner's range and the first spawn.
     * @param minDelay The minimum delay between two spawns.
     * @param maxDelay The maximum delay between two spawns.
     * @param spawnCount The amount of Entities spawned every spawn.
     * @param spawnRange The range (cuboid with height 3 and remaining sides of range) in which spawned Entities should be placed.
     * @param maxNearbyEntities If this or a greater number of Entities is within the spawner's spawn range, it will stop spawning Entities.
     * @param minPlayerDistance The minimum distance between a player and the spawner at which the spawner should activate.
     * @param spawnerLogic A reference to the spawner's logic.
     */
    public static void setSpawnerSpecifics(String mobID, int initialSpawnDelay, int minDelay, int maxDelay, int spawnCount, int spawnRange, int maxNearbyEntities, int minPlayerDistance, MobSpawnerBaseLogic spawnerLogic) {
        setMobID(mobID, spawnerLogic);
        setInitialSpawnDelay(initialSpawnDelay, spawnerLogic);
        setMinDelay(minDelay, spawnerLogic);
        setMaxDelay(maxDelay, spawnerLogic);
        setSpawnCount(spawnCount, spawnerLogic);
        setSpawnRange(spawnRange, spawnerLogic);
        setMaxNearbyEntities(maxNearbyEntities, spawnerLogic);
        setMinPlayerDistance(minPlayerDistance, spawnerLogic);
    }

    /**
     *
     * @param entity The entity to spawn.
     * @param initialSpawnDelay The delay (in ticks) between when the player first enters the spawner's range and the first spawn.
     * @param minDelay The minimum delay between two spawns.
     * @param maxDelay The maximum delay between two spawns.
     * @param spawnCount The amount of Entities spawned every spawn.
     * @param spawnRange The range (cuboid with height 3 and remaining sides of range) in which spawned Entities should be placed.
     * @param maxNearbyEntities If this or a greater number of Entities is within the spawner's spawn range, it will stop spawning Entities.
     * @param minPlayerDistance The minimum distance between a player and the spawner at which the spawner should activate.
     * @param spawnerLogic A reference to the spawner's logic.
     */
    public static void setSpawnerSpecifics(EntityLiving entity, int initialSpawnDelay, int minDelay, int maxDelay, int spawnCount, int spawnRange, int maxNearbyEntities, int minPlayerDistance, MobSpawnerBaseLogic spawnerLogic) {
        NBTTagCompound compound = new NBTTagCompound();
        entity.writeEntityToNBT(compound);
        setNBT(entity.getName(), compound, spawnerLogic);
        setInitialSpawnDelay(initialSpawnDelay, spawnerLogic);
        setMinDelay(minDelay, spawnerLogic);
        setMaxDelay(maxDelay, spawnerLogic);
        setSpawnCount(spawnCount, spawnerLogic);
        setSpawnRange(spawnRange, spawnerLogic);
        setMaxNearbyEntities(maxNearbyEntities, spawnerLogic);
        setMinPlayerDistance(minPlayerDistance, spawnerLogic);
    }

    private static void setMobID(String id, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("mobID");
            field.setAccessible(true);
            field.set(obj, id);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setInitialSpawnDelay(int delay, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("spawnDelay");
            field.setAccessible(true);
            field.set(obj, delay);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setMinDelay(int delay, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("minSpawnDelay");
            field.setAccessible(true);
            field.set(obj, delay);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setMaxDelay(int delay, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("maxSpawnDelay");
            field.setAccessible(true);
            field.set(obj, delay);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setSpawnCount(int count, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("spawnCount");
            field.setAccessible(true);
            field.set(obj, count);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setSpawnRange(int range, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("spawnRange");
            field.setAccessible(true);
            field.set(obj, range);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setMaxNearbyEntities(int count, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("maxNearbyEntities");
            field.setAccessible(true);
            field.set(obj, count);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    private static void setMinPlayerDistance(int distance, MobSpawnerBaseLogic obj) {
        try {
            Field field = MobSpawnerBaseLogic.class.getDeclaredField("activatingRangeFromPlayer");
            field.setAccessible(true);
            field.set(obj, distance);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("JavaReflectionMemberAccess")
    private static void setNBT(String mobID, NBTTagCompound compound, MobSpawnerBaseLogic obj) {
        try {
            Constructor constructor = MobSpawnerBaseLogic.WeightedRandomMinecart.class.getDeclaredConstructor(MobSpawnerBaseLogic.class, NBTTagCompound.class, String.class);
            Field randomEntity = MobSpawnerBaseLogic.class.getDeclaredField("randomEntity");
            randomEntity.setAccessible(true);
            randomEntity.set(obj, constructor.newInstance(obj, compound, mobID));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

 

 

An implementation of the methods:

Spoiler

EntityZombie zombie1 = new EntityZombie(world);
applyRandomTierFourArmour(zombie1);
for (int i = 0; i < 5; i++) {
    zombie1.setEquipmentDropChance(i, 0);
}
zombie1.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 1000000, 0));
world.setBlockState(origin.add(6, 1, 6), Blocks.mob_spawner.getDefaultState());
setSpawnerSpecifics(zombie1, 0, 40, 100, 1, 16, 8, 16, ((TileEntityMobSpawner) world.getTileEntity(origin.add(6, 1, 6))).getSpawnerBaseLogic());

world.setBlockState(origin.add(11, 18, 11), Blocks.mob_spawner.getDefaultState());
setSpawnerSpecifics("em.ice_cube", 0, 100, 200, 3, 10, 8, 11, ((TileEntityMobSpawner) world.getTileEntity(origin.add(11, 18, 11))).getSpawnerBaseLogic());

 

 

Edited by JoieNL
Link to comment
Share on other sites

I think an important option you've failed to consider is you don't need to use the vanilla mob spawner, rather you can create your own custom ones that extend the vanilla one , and have those placed during structure generation, and have them do the initial logic you want (or otherwise expose the private fields through setter and getter methods), etc. I'm not exactly sure why you need to do the reflection part.  

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

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

    • Are you using Fabric? I'm not sure if this forum would be the right place then.
    • server failed to start and gives me "Failed to load data packs, can't proceed with server load. You can either fix your data packs or reset to vanilla with --safeMode" error when i look in my logs. its updated to the latest version of forge(40.1.0), and I don't have any data packs installed as far as I know. And I will upload the full logs if asked as i dont know how to attach a document to this post.  
    • Pioneer Craft [modded] {1.18.2} {SMP} {Community} {Light Roleplay} We are Pioneer Craft and we seek you !!! We are building a community of passionate players to build, trade, and share some laughs with. Are you tired of playing alone? Or are you here seeking a server with dedicated members; a server where you are not overlooked and can voice your opinions? If you are interested in these things too, then come join us in Pioneer Craft! Our server is player built and driven. We have a custom mod pack with mods chosen by our community to suit our needs. We have designed our server for player driven roleplay! There will be four communities which will each be self-sufficient. We encourage and seek builders who want to create a beautiful world to live in. This is a whitelist server and we are looking for dedicated applicants and experienced builders. Applications are located on our website which can be accessed through the discord. Other than the application questions, we are requesting photos of your prior builds which will be taken into consideration. Please show photos of your builds in the share-your-work section of the discord. The server uses CurseForge to run. This server is for mature members (16+) . Discord (must join): https://discord.gg/c4uJvb29CN
    • Pioneer Craft [modded] {1.18.2} {SMP} {Community} {Light Roleplay} We are Pioneer Craft and we seek you !!! We are building a community of passionate players to build, trade, and share some laughs with. Are you tired of playing alone? Or are you here seeking a server with dedicated members; a server where you are not overlooked and can voice your opinions? If you are interested in these things too, then come join us in Pioneer Craft! Our server is player built and driven. We have a custom mod pack with mods chosen by our community to suit our needs. We have designed our server for player driven roleplay! There will be four communities which will each be self-sufficient. We encourage and seek builders who want to create a beautiful world to live in. This is a whitelist server and we are looking for dedicated applicants and experienced builders. Applications are located on our website which can be accessed through the discord. Other than the application questions, we are requesting photos of your prior builds which will be taken into consideration. Please show photos of your builds in the share-your-work section of the discord. The server uses CurseForge to run. This server is for mature members (16+) . Discord (must join): https://discord.gg/c4uJvb29CN 
    • Update: I didn't need capabilities. In fact, I didn't need to override applyEffectTick at all. But it seems like I need reflections. The increased hitbox size now works for both entity and block collision--with a little drawback. This is what it looks like so far: // this event handler checks every tick if the living entity has the "big" effect @SubscribeEvent public static void entitySizeChange(LivingEvent.LivingUpdateEvent event) { LivingEntity livingEntity = event.getEntityLiving(); if (livingEntity.getActiveEffectsMap() != null && livingEntity.hasEffect(ModEffects.BIG.get())) { EntityDimensions newDims = livingEntity.getDimensions(livingEntity.getPose()).scale(8.0F, 2.0F); try { // using reflection Field field = Entity.class.getDeclaredField("dimensions"); field.setAccessible(true); field.set(livingEntity, newDims); // setting the living entity's EntityDimensions EntityDimensions newEntityDimensions = (EntityDimensions) field.get(livingEntity); livingEntity.setBoundingBox(newEntityDimensions.makeBoundingBox( // setting the living entity's AABB livingEntity.getX(), livingEntity.getY(), livingEntity.getZ() )); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } }   The aforementioned drawback is that, when the effect wears off, the living entity's still keeps its bigger hitbox until it changes pose (i.e. my player crouching). Given that the EntityEvent.Size event fires whenever an entity changes pose, should I manually fire it with EVENT_BUS::post when that entity's effect wears off? If so, where? I tried manually firing EntityEvent.Size on my overridden removeAttributeModifiers(), but to no avail. 
  • Topics

×
×
  • Create New...

Important Information

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