Is there a way to detect if there any mobs of a certain type near a location?

Discussion in 'Plugin Development' started by Kamisoyokaze, May 28, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    Kamisoyokaze

    I need to check if there are any mobs of the same type within say... 100 blocks of where a mob is spawning, how can I do this?
     
  2. Offline

    suckycomedian

    Code:java
    1. @EventHandler
    2. public void monsterSpawn(CreatureSpawnEvent event){
    3. Entity entity = event.getEntity();
    4. Location monLoc = event.getLocation();
    5.  
    6. final Collection<Entity> entities = entity.getWorld().getEntities();
    7. final double monLocX = monLoc.getX();
    8. final double monLocZ = monLoc.getZ();
    9. final double monLocY = monLoc.getY();
    10. final int radiusX = 50;
    11. final int radiusZ = 50;
    12. final int radiusY = 4;
    13.  
    14. for(final Entity ent : entities){
    15. if(ent instanceof Monster){ //or you could do LivingEntity if it's for any mob..
    16. Location loc = ent.getLocation();
    17. if(((monLocX + radiusX) > loc.getX() && loc.getX() > (monLocX - radiusX)) && ((monLocZ + radiusZ) > loc.getZ() && loc.getZ() > (monLocZ - radiusZ)) && ((monLocY + radiusY) > loc.getY() && loc.getY() > (monLocY - radiusY))){
    18. //do something
    19. }
    20. }
    21. }
    22. }
     
    Kamisoyokaze likes this.
  3. Offline

    Kamisoyokaze

    Oh cheers mate, big help :) I'll test it out once I get back from my programming exam at college >.>​
     
  4. @suckycomedianYou know about getNearbyEntities() ? You can shorten your code by using it instead of checking all entities in the world. ;)
    Code:java
    1. public void monsterSpawn(CreatureSpawnEvent event){
    2. for(Entity ent: event.getEntity().getNearbyEntities(50.0D, 4.0D, 50.0D)){
    3. if(ent instanceof Monster){ //or you could do LivingEntity if it's for any mob..
    4. //do something
    5. }
    6. }
    7. }
     
  5. Offline

    suckycomedian

    Yeah, but I copied and pasted (with some changes) this from a teleport plugin I made that stops you from teleporting to a location if there are monsters within a certain amount of blocks fromm the destination and getNearbyEntities wouldn't work right for that. Idk if it will for what he's doing. It might since I had to do that to make sure to check the destination.. Idk
     
Thread Status:
Not open for further replies.

Share This Page