Getting Entity Player Is Looking At

Discussion in 'Plugin Development' started by iWareWolf, Apr 29, 2014.

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

    iWareWolf

    How can I get the entity a player is looking at from a distance away?
     
  2. Offline

    thecrystalflame

    the only real way to do this is with a RayTrace, there are many ways to do this. and it is fairly advanced.

    the other way i see this done allot is by spawning an invisible snowball with a multiplied velocity and returning the entity that that snowball hits. i wouldnt recomend doing this because of the way snowballs fly, the accuracy and efficiency of this method is little above terrible.

    raytracing uses bounding boxes, the easiest kind to use would be to make a custom AABB object that you can create for each entity.

    i wont get into to much detail now, as i dont really want to swamp you with ideas that may confuse you. if you do need that extra help on how to do this send me a message and ill get back to you.
     
  3. Offline

    Jordymt

    I've been using this lately, I don't know anymore who made it but it is from the Bukkit forum. All credits to the guy who made it ofcourse.
    Code:java
    1. public LivingEntity getTarget(Player player) {
    2. int range = 60;
    3. List<Entity> nearbyE = player.getNearbyEntities(range, range, range);
    4. ArrayList<LivingEntity> livingE = new ArrayList<LivingEntity>();
    5.  
    6. for (Entity e : nearbyE) {
    7. if (e instanceof LivingEntity) {
    8. livingE.add((LivingEntity) e);
    9. }
    10. }
    11.  
    12. LivingEntity target = null;
    13. BlockIterator bItr = new BlockIterator(player, range);
    14. Block block;
    15. Location loc;
    16. int bx, by, bz;
    17. double ex, ey, ez;
    18. // loop through player's line of sight
    19. while (bItr.hasNext()) {
    20. block = bItr.next();
    21. bx = block.getX();
    22. by = block.getY();
    23. bz = block.getZ();
    24. // check for entities near this block in the line of sight
    25. for (LivingEntity e : livingE) {
    26. loc = e.getLocation();
    27. ex = loc.getX();
    28. ey = loc.getY();
    29. ez = loc.getZ();
    30. if ((bx - .75 <= ex && ex <= bx + 1.75)
    31. && (bz - .75 <= ez && ez <= bz + 1.75)
    32. && (by - 1 <= ey && ey <= by + 2.5)) {
    33. // entity is close enough, set target and stop
    34. target = e;
    35. break;
    36. }
    37. }
    38. }
    39. return target;
    40.  
    41. }


    And then get the target like this:
    Code:java
    1. Entity entity = getTarget(p);
    2. Player target = (Player)entity;
     
Thread Status:
Not open for further replies.

Share This Page