Jump to content

Mob Flocking AI...


Captain Hillman

Recommended Posts

I'm trying to implement a generic Flocking AI that I can use for any new creatures I add to my mod in the future. I've followed the flocking information found here (http://bit.ly/1kOI2ul) and implemented it with the code below. However, my creatures don't move at all (except for occasionally falling through the floor).

 

Anyone have any idea where I'm going wrong? If anyone's got any posts/tutorials on group-movement of creatures, that'd be handy too :)

 

FlockUtils.java

 

public class FlockUtils {

 

  public static Point2D.Double computeAlignment(Entity creature, int blockRadius) {

      Point2D.Double target = new Point2D.Double();

      int neighbours = 0;

     

      double x = creature.posX;

      double y = creature.posY;

      double z = creature.posZ;

     

      AxisAlignedBB boundingBox = AxisAlignedBB.getAABBPool().getAABB(x, y, z, x + 1, y + 1, z + 1);

      boundingBox = boundingBox.expand(blockRadius, blockRadius, blockRadius);

     

      List<Entity> entities = creature.worldObj.getEntitiesWithinAABB(Entity.class, boundingBox);

     

      for(Entity entity : entities) {

        if( !entity.equals(creature) && entity.getClass().equals(creature.getClass()) ) {

            target.x += entity.motionX;

            target.y += entity.motionZ;

            neighbours++;

        }

      }

     

      if(neighbours == 0) {

        return target;

      }

      target.x /= neighbours;

      target.y /= neighbours;

     

      double length = Math.sqrt((target.x * target.x) + (target.y * target.y));

      target.x /= length;

      target.y /= length;

      return target;

  }

 

  public static Point2D.Double computeCohesion(Entity creature, int blockRadius) {

      Point2D.Double target = new Point2D.Double();

      int neighbours = 0;

     

      double x = creature.posX;

      double y = creature.posY;

      double z = creature.posZ;

     

      AxisAlignedBB boundingBox = AxisAlignedBB.getAABBPool().getAABB(x, y, z, x + 1, y + 1, z + 1);

      boundingBox = boundingBox.expand(blockRadius, blockRadius, blockRadius);

     

      List<Entity> entities = creature.worldObj.getEntitiesWithinAABB(Entity.class, boundingBox);

     

      for(Entity entity : entities) {

        if( !entity.equals(creature) && entity.getClass().equals(creature.getClass()) ) {

            target.x += entity.posX;

            target.y += entity.posZ;

            neighbours++;

        }

      }

     

      if(neighbours == 0) {

        return target;

      }

      target.x /= neighbours;

      target.y /= neighbours;

     

      target = new Point2D.Double(target.x - creature.posX, target.y - creature.posZ);

     

      double length = Math.sqrt((target.x * target.x) + (target.y * target.y));

      target.x /= length;

      target.y /= length;

      return target;

  }

 

  public static Point2D.Double computeSeparation(Entity creature, int blockRadius) {

      Point2D.Double target = new Point2D.Double();

      int neighbours = 0;

     

      double x = creature.posX;

      double y = creature.posY;

      double z = creature.posZ;

     

      AxisAlignedBB boundingBox = AxisAlignedBB.getAABBPool().getAABB(x, y, z, x + 1, y + 1, z + 1);

      boundingBox = boundingBox.expand(blockRadius, blockRadius, blockRadius);

     

      List<Entity> entities = creature.worldObj.getEntitiesWithinAABB(Entity.class, boundingBox);

     

      for(Entity entity : entities) {

        if( !entity.equals(creature) && entity.getClass().equals(creature.getClass()) ) {

            target.x -= entity.posX;

            target.y -= entity.posZ;

            neighbours++;

        }

      }

     

      if(neighbours == 0) {

        return target;

      }

      target.x /= neighbours;

      target.y /= neighbours;

     

      target = new Point2D.Double((target.x - creature.posX) * -1, (target.y - creature.posZ) * -1);

     

      double length = Math.sqrt((target.x * target.x) + (target.y * target.y));

      target.x /= length;

      target.y /= length;

      return target;

  }

}

 

 

FlockAI.java

 

public class FlockAI extends EntityAIBase {

 

private EntityCreature entity;

    private double xPosition;

    private double yPosition;

    private double zPosition;

    private double speed;

 

    public FlockAI(EntityCreature par1EntityCreature, double par2) {

        this.entity = par1EntityCreature;

        this.speed = par2;

        this.setMutexBits(1);

    }

 

    @Override

    public boolean shouldExecute() {

        if(entity.getAge() >= 100) {

            return false;

           

        } else if (entity.getRNG().nextInt(120) != 0) {

            return false;

           

        } else {

            Vec3 vec3 = RandomPositionGenerator.findRandomTarget(entity, 10, 7);

 

            if(vec3 == null) {

                return false;

               

            } else {

                xPosition = vec3.xCoord;

                yPosition = vec3.yCoord;

                zPosition = vec3.zCoord;

                return true;

            }

        }

    }

 

    @Override

    public boolean continueExecuting() {

    return !this.entity.getNavigator().noPath();

    }

 

    @Override

    public void startExecuting() {

    entity.getNavigator().tryMoveToXYZ(xPosition, yPosition, zPosition, speed);

    }

   

    @Override

    public void updateTask() {

    if(!continueExecuting()) {

    return;

    }

    Point2D.Double alignment = FlockUtils.computeAlignment(entity, 5);

    Point2D.Double cohesion = FlockUtils.computeCohesion(entity, 5);

    Point2D.Double separation = FlockUtils.computeSeparation(entity, 5);

   

    entity.motionX += alignment.x + cohesion.x + separation.x;

    entity.motionZ += alignment.y + cohesion.y + separation.y;

   

    //Normalise it.

    double length = Math.sqrt((entity.motionX * entity.motionX) + (entity.motionZ * entity.motionZ));

    entity.motionX /= length;

    entity.motionZ /= length;

    }

}

 

Link to comment
Share on other sites

How did you register your AI to your entity? Can you show that code?  (You should be adding it to the tasks list and assign it an appropriate priority.)

 

I think you should take out the randomization until you have it working a bit more.  Your current code will only on average fire once every six seconds!

 

Also, if you're having this AI run together with other AI then you may need to look at how you set the mutexBits.  I recently figured out how those work.  Basically, you don't want two different movement AI active at the same time or each will be interfering with the other, and same with attacking, etc.  Swimming is compatible with some things but not others.  Anyway, see the last post on this thread about how to set the mutexBits: http://www.minecraftforge.net/forum/index.php?topic=18777.0.  In your case I think it mutexBits should be set to 1 (like other movement AI).

 

Lastly, you should put console System.out.println() statements in your code to confirm whether it is executing at all, and how.  I usually put in a statement in each method to at least indicate that the method was run with something like "running Flock AI startExecuting()" type statements.  And I would put such statements inside each if-else-if so you can trace which path is followed.  It is usually pretty clear once you see those what is happening.

 

Overall, for your AI to execute it needs to be in the task list, it needs to have higher priority (lower number) in that list than other movement AI tasks, and the shouldExecute() method needs to return true.  Also, you the continueExecuting() method needs to return true for as long as the AI is supposed to continue.

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

    • I'm using Modrinth as a launcher for a forge modpack on 1.20.1, and can't diagnose the issue on the crash log myself. Have tried repairing the Minecraft instillation as well as removing a few mods that have been problematic for me in the past to no avail. Crash log is below, if any further information is necessary let me know. Thank you! https://paste.ee/p/k6xnS
    • Hey folks. I am working on a custom "Mecha" entity (extended from LivingEntity) that the player builds up from blocks that should get modular stats depending on the used blocks. e.g. depending on what will be used for the legs, the entity will have a different jump strength. However, something unexpected is happening when trying to override a few of LivingEntity's functions and using my new own "Mecha" specific fields: instead of their actual instance-specific value, the default value is used (0f for a float, null for an object...) This is especially strange as when executing with the same entity from a point in the code specific to the mecha entity, the correct value is used. Here are some code snippets to better illustrate what I mean: /* The main Mecha class, cut down for brevity */ public class Mecha extends LivingEntity { protected float jumpMultiplier; //somewhere later during the code when spawning the entity, jumpMultiplier is set to something like 1.5f //changing the access to public didn't help @Override //Overridden from LivingEntity, this function is only used in the jumpFromGround() function, used in the aiStep() function, used in the LivingEntity tick() function protected float getJumpPower() { //something is wrong with this function //for some reason I can't correctly access the fields and methods from the instanciated entity when I am in one of those overridden protected functions. this is very annoying LogUtils.getLogger().info(String.valueOf(this.jumpMultiplier))) //will print 0f return this.jumpMultiplier * super.getJumpPower(); } //The code above does not operate properly. Written as is, the entity will not jump, and adding debug logs shows that when executing the code, the value of this.jumpMultiplier is 0f //in contrast, it will be the correct value when done here: @Override public void tick() { super.tick(); //inherited LivingEntity logic //Custom logic LogUtils.getLogger().info(String.valueOf(this.jumpMultiplier))) //will print 1.5f } } My actual code is slightly different, as the jumpMuliplier is stored in another object (so I am calling "this.legModule.getJumpPower()" instead of the float), but even using a simple float exactly like in the code above didn't help. When running my usual code, the object I try to use is found to be null instead, leading to a crash from a nullPointerException. Here is the stacktrace of said crash: The full code can be viewed here. I have found a workaround in the case of jump strength, but have already found the same problem for another parameter I want to do, and I do not understand why the code is behaving as such, and I would very much like to be able to override those methods as intended - they seemed to work just fine like that for vanilla mobs... Any clues as to what may be happening here?
    • Please delete post. Had not noticed the newest edition for 1.20.6 which resolves the issue.
    • https://paste.ee/p/GTgAV Here's my debug log, I'm on 1.18.2 with forge 40.2.4 and I just want to get it to work!! I cant find any mod names in the error part and I would like some help from the pros!! I have 203 mods at the moment.
  • Topics

×
×
  • Create New...

Important Information

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