Follow idea

Discussion in 'Plugin Development' started by user_91277742, Jun 8, 2019.

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

    user_91277742

    Hi there!
    I need a command to let an entity to follow the player, but the problem is.. what can i do? , some idea?
     
  2. Offline

    Tango_

    I've done something like this before, you should put the player and entity into a hashmap, (probably by their UUIDs) and then on PlayerMoveEvent, check if the player moved 1 block, then apply velocity to the entity towards the player. This is better than teleporting because its more smooth and looks like the entity is moving towards the player.

    Something like this:

    Code:
            Player player = e.getPlayer();
    
            if(hashmap.containsKey(player.getUniqueId())) {
         
                Entity entity = (get entity linked to player from hashmap);
                Location location = entity.getLocation();
    
                double speed = 0.5;
                Vector dir = location.toVector().subtract(player.getLocation().toVector()).normalize();
    
                entity.setVelocity(dir.multiply(speed));
    
            }
     
    Last edited: Jun 8, 2019
  3. Offline

    timtower Moderator Moderator

    @Tango_ How does it react with height differences?
     
  4. Offline

    Tango_

    What do you mean, like jumping over blocks?
     
  5. Offline

    timtower Moderator Moderator

    Yes, and overal gaps.
     
  6. Offline

    Tango_

    Well I didn't want to give too much code since I just intended to point in the right direction, but this is what I used to detect if the entity needs to jump, I set velocity on the Y level.


    Code:
                if(e.getTo().getBlockX() == e.getFrom().getBlockX()
                        && e.getTo().getBlockZ() == e.getFrom().getBlockZ()
                        && e.getTo().getBlockY() == e.getFrom().getBlockY()
                        && distance > 4
                        && entity.getLocation().getBlock().getRelative(BlockFace.DOWN).getType() != Material.AIR) {
                  
                    entity.setVelocity(entity.getVelocity().setY(0.2));
                  
                }
     
    Last edited: Jun 8, 2019
  7. Offline

    bwfcwalshy Retired Staff

    @Tango_ If you're suggesting to do that in PlayerMoveEvent then I'd optimise a bit more. Simple things like getting from map and doing a null check instead of a contains (which essentially runs get and a null check).

    I'd probably just do setTarget, let MC handle the following in the same way mobs usually work.
     
Thread Status:
Not open for further replies.

Share This Page