Jump to content

[SOLVED] [1.10] Find a tile entity within a AABB bounding box placed when an event happens


MSpace-Dev

Recommended Posts

Hello everyone,

 

So, I am making a block that needs to check when any mobs spawn around it. What I want to do is when this LivingSpawnEvent happens, is create an AABB at this event's position, and CHECK if my tile entity is within this box. I have no idea how to do this, and I've tried scouring the web, with no success. I'm also not sure how to create my AABB at this specific event's coords. This is what I have so far.

 

EVENT HANDLER:

@Mod.EventBusSubscriber
public class MonsterTotemsEventHandler {
    @SubscribeEvent
    public void mobSpawn(LivingSpawnEvent e) {
        BlockPos eventPos = e.getEntity().getPosition();
        AxisAlignedBB eventAABB = new AxisAlignedBB(10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f);
      	// if (tile entity is in AABB) {
    	//	execute code here
    	//}
    }
}

 

Thanks!

Edited by MSpace-Dev
Topic Solved
Link to comment
Share on other sites

You can call BlockPos#getAllInBox which returns a collection of BlockPos. You need to give the method 2 opposite corners. You can get those by using BlockPos::add(+-x, +-y, +-z)

You can then do a normal for-loop or lambda-for-each to iterate over each BlockPos.

  • Like 1

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Link to comment
Share on other sites

Awesome, that has helped a lot! Just one thing, I am new to Tile Entities. So, I am not sure how to reference the Tile Entity that I'm looking for. I have "bound" the Tile Entity to the block, using the createTileEntity() method. From here, do I just check for the blockstate, or do I search for the tile entity? Here is my code so far

@Mod.EventBusSubscriber
public class MonsterTotemsEventHandler {
    @SubscribeEvent
    public void mobSpawn(LivingSpawnEvent e) {
        BlockPos eventPos = e.getEntity().getPosition();
        Iterable<BlockPos> blocks = BlockPos.getAllInBox(eventPos.add(-10.0f, -10.0f, -10.0f), eventPos.add(10.0f, 10.0f, 10.0f));

        for (BlockPos pos : blocks) {
            World world = e.getWorld();
            if(world.getTileEntity(pos) == ){ // Not sure what to put here <<
				// execute code
            }
        }
    }
}

 

Link to comment
Share on other sites

Well, not all blocks have tileentities. In those cases, World::getTileEntity will return null, so you'll need a null-check first, or you'll very likely crash. After that, you can use an instanceof instead of equals-check, and just reference your TileEntity's type eg if(world.getTileEntity(pos) instanceof TileEntityFurnace)

Edited by Matryoshika
  • Like 1

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Link to comment
Share on other sites

So, I'm getting this error when in-game.

A TileEntity type io.github.mspacedev.tiles.TileEntityTotemBase has throw an exception trying to write state. It will not persist. Report this to the mod author
java.lang.RuntimeException: class io.github.mspacedev.tiles.TileEntityTotemBase is missing a mapping!

Even though, I have reason to believe, that I have mapped the Tile Entity. (Again, new to this)

 

BLOCK CLASS:

public class BlockTotemBase extends BlockBase implements ITileEntityProvider {

    public BlockTotemBase(String name, Material materialIn) {
        super(name, materialIn);
    }

    @Nullable
    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta) {
        return new TileEntityTotemBase();
    }
}

 

TILE ENTITY TOTEM BASE:

public class TileEntityTotemBase extends TileEntity {
	// Empty
}

 

MAIN CLASS INIT: (removed a bunch of unnecessary code, that does not need to be seen)

@Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION )
public class MonsterTotems {
    public static void init(FMLInitializationEvent event){
        proxy.init(event);
        ModTileEntities.init();
    }
}

 

MOD TILE ENTITIES:

public class ModTileEntities {

    public static void init(){
        GameRegistry.registerTileEntity(TileEntityTotemBase.class, "totem_base_i");
    }
}

 

Btw, I register the BlockTotemBase with the same id as the Tile Entity.

Link to comment
Share on other sites

6 minutes ago, MSpace-Dev said:

MAIN CLASS INIT: (removed a bunch of unnecessary code, that does not need to be seen)


@Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION )
public class MonsterTotems {
    public static void init(FMLInitializationEvent event){
        proxy.init(event);
        ModTileEntities.init();
    }
}

 

You need to make your init method non-static and you need to add @Mod.EventHandler on top of the method.

Edited by larsgerrits
  • Like 1

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

I've done that. Still get the same error.

 

MAIN CLASS:

public void init(FMLInitializationEvent event){
        proxy.init(event);
        ModTileEntities.init();
    }

 

MOD TILE ENTITIES:

public class ModTileEntities {

    @Mod.EventHandler
    public static void init(){
        GameRegistry.registerTileEntity(TileEntityTotemBase.class, "totem_base_i_te");
    }
}

 

Link to comment
Share on other sites

3 minutes ago, MSpace-Dev said:

I've done that. Still get the same error.

 

MAIN CLASS:


public void init(FMLInitializationEvent event){
        proxy.init(event);
        ModTileEntities.init();
    }

 

MOD TILE ENTITIES:


public class ModTileEntities {

    @Mod.EventHandler
    public static void init(){
        GameRegistry.registerTileEntity(TileEntityTotemBase.class, "totem_base_i_te");
    }
}

 

No, add @Mod.EventHandler on top of the init method in your @Mod class.

  • Like 1

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

Awesome, finally got that working. Geez, sorry about that... 

Now that that is out of the way, back to my main question. I have got this so far:

 

MONSTER TOTEMS EVENT HANDLER:

@Mod.EventBusSubscriber
public class MonsterTotemsEventHandler {
    @SubscribeEvent
    public void mobSpawn(LivingSpawnEvent e) {
      	Utils.getLogger().info("MOB SPAWNED!!!");

        BlockPos eventPos = e.getEntity().getPosition();
        Iterable<BlockPos> blocks = BlockPos.getAllInBox(eventPos.add(-100.0f, -100.0f, -100.0f), eventPos.add(100.0f, 100.0f, 100.0f));

        for (BlockPos pos : blocks) {
            World world = e.getWorld();
            if(world.getTileEntity(pos) != null) {
                if (world.getTileEntity(pos) instanceof TileEntityTotemBase) {
                    e.getEntity().setFire(100);
                  	Utils.getLogger().info("MOB CLOSE TO TILE ENTITY!!!");
                }
            }
        }
    }
}

 

Anyways, long-story-short, none of the logger messages get outputted to the console, when a mob spawns during night time. Which means this event handler isn't working.

 

MAIN CLASS: (postInit())

public void postInit(FMLPostInitializationEvent event){
        proxy.postInit(event);
        MinecraftForge.EVENT_BUS.register(new MonsterTotemsEventHandler());
    }

 

EDIT: I need @Mod.EventHandler on top... don't I...?

Edited by MSpace-Dev
Link to comment
Share on other sites

4 minutes ago, MSpace-Dev said:

EDIT: I need @Mod.EventHandler on top... don't I...?

Yes, you need it on top of all the FML lifecycle events.

  • Like 1

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Link to comment
Share on other sites

  • 2 months later...
On 17.12.2017 at 0:12 AM, diesieben07 said:
  • Problematic code issue 4 and 10.
  • instanceof includes a null check already, you do not need a separate one.
  • There is a much more efficient way to check for TileEntities in an area, since every Chunk has a list of it's TileEntities (Chunk::getTileEntityMap). You can just get all Chunks that fall within your area and only check the TileEntities within them, instead of every single block position. This is particularly important since you are doing this on every mob spawn (this happens a lot!). For something even more efficient you could add a chunk capability and use it to store only your TileEntities within that chunk, which would allow you to only check that map.

 

I've read through the docs but it's still kinda hazy for me, wouldn't it require a fair amount of workaround to add a capability to such an important part of vanilla code?

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

    • https://pastebin.com/VwpAW6PX My game crashes upon launch when trying to implement the Oculus mod to this mod compilation, above is the crash report, I do not know where to begin to attempt to fix this issue and require assistance.
    • https://youtube.com/shorts/gqLTSMymgUg?si=5QOeSvA4TTs-bL46
    • CubeHaven is a SMP server with unique features that can't be found on the majority of other servers! Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132 3 different stores: - CubeHaven Store: Our store to purchase using real money. - Bitcoin Store: Store for Bitcoin. Bitcoin can be earned from playing the server. Giving options for players if they want to spend real money or grind to obtain exclusive packages. - Black Market: A hidden store for trading that operates outside our traditional stores, like custom enchantments, exclusive items and more. Some of our features include: Rank Up: Progress through different ranks to unlock new privileges and perks. 📈 Skills: RPG-style skill system that enhances your gaming experience! 🎮 Leaderboards: Compete and shine! Top players are rewarded weekly! 🏆 Random Teleporter: Travel instantly across different worlds with a click! 🌐 Custom World Generation: Beautifully generated world. 🌍 Dungeons: Explore challenging and rewarding dungeons filled with treasures and monsters. 🏰 Kits: Unlock ranks and gain access to various kits. 🛠️ Fishing Tournament: Compete in a friendly fishing tournament! 🎣 Chat Games: Enjoy games right within the chat! 🎲 Minions: Get some help from your loyal minions. 👥 Piñata Party: Enjoy a festive party with Piñatas! 🎉 Quests: Over 1000 quests that you can complete! 📜 Bounty Hunter: Set a bounty on a player's head. 💰 Tags: Displayed on nametags, in the tab list, and in chat. 🏷️ Coinflip: Bet with other players on coin toss outcomes, victory, or defeat! 🟢 Invisible & Glowing Frames: Hide your frames for a cleaner look or apply a glow to it for a beautiful look. 🔲✨[ Player Warp: Set your own warp points for other players to teleport to. 🌟 Display Shop: Create your own shop and sell to other players! 🛒 Item Skins: Customize your items with unique skins. 🎨 Pets: Your cute loyal companion to follow you wherever you go! 🐾 Cosmetics: Enhance the look of your character with beautiful cosmetics! 💄 XP-Bottle: Store your exp safely in a bottle for later use! 🍶 Chest & Inventory Sorting: Keep your items neatly sorted in your inventory or chest! 📦 Glowing: Stand out from other players with a colorful glow! ✨ Player Particles: Over 100 unique particle effects to show off. 🎇 Portable Inventories: Over virtual inventories with ease. 🧳 And a lot more! Become part of our growing community today! Discord: https://cubehaven.net/discord Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132
    • # Problematic frame: # C [libopenal.so+0x9fb4d] It is always the same issue - this refers to the Linux OS - so your system may prevent Java from working   I am not familiar with Linux - check for similar/related issues  
  • Topics

×
×
  • Create New...

Important Information

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