1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

Better way of taking care about at which entity the player looks

Discussion in 'Development' started by kniffo80, Mar 9, 2017.

  1. kniffo80

    kniffo80 Silverfish

    Messages:
    24
    GitHub:
    kniffo80
    Hi specialists,

    I'm looking for a better way to find out at which entity the player is looking currently. At the moment I'm using the following code by using the BlockIterator:

    PHP:
    public static function getEntityPlayerLookingAt(Player $playerint $maxDistancebool $useCorrection false) {
            
    /**
             * @var Entity
             */
            
    $entity null;

            
    $nearbyEntities $player->getLevel()->getNearbyEntities($player->boundingBox->grow($maxDistance$maxDistance$maxDistance), $player);

            
    // get all blocks in looking direction until the max interact distance is reached (it's possible that startblock isn't found!)
            
    try {
                
    $itr = new BlockIterator($player->level$player->getPosition(), $player->getDirectionVector(), $player->getEyeHeight(), $maxDistance);
            } catch (
    InvalidStateException $e) {
                
    // nothing to log here!
            
    }
            if (
    $itr !== null) {
                
    $block null;
                
    $entity null;
                while (
    $itr->valid()) {
                    
    $itr->next();
                    
    $block $itr->current();
                    
    $entity self::getEntityAtPosition($nearbyEntities$block->x$block->y$block->z$useCorrection);
                    if (
    $entity !== null) {
                        break;
                    }
                }
            }

            return 
    $entity;
        }
    I've a simple question, as it's of course a performance issue doing this all the time using getNearbyEntities and the BlockIterator. Especially when i want to know if a player is looking at an enderman e.g.

    So just a simple question: is there a better, more performant way to do this?
     
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.