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

Solved Get Entity in line of sight

Discussion in 'Development' started by Moonafic, Jan 2, 2021.

  1. Moonafic

    Moonafic Silverfish

    Messages:
    24
    Can i get entity when im looking exactly at its bounding box? Using $living->getTarget Block() and $level->getNearestEntity() doesnt work properly.
    I tried getting block, creating AxisAlignedBB on top of it and search for entities in it but this wasn't good as i expected. Is that the only way to do it by getting target block?

    sorry for bad english
     
    Last edited: Jan 2, 2021
  2. ethaniccc

    ethaniccc Baby Zombie

    Messages:
    189
    GitHub:
    ethaniccc
    NOTE: This is going to be heavy on performance

    First, make an expanded copy of the player's AABB, expanding it by the distance you want to traverse (so if I want to get entities within a 3 block radius, I would expand the AABB by 3, 3, 3). Then, using Level->getCollidingEntities(), get the nearby entities (you can leave the second parameter empty).
    Once you have all the nearby entities, using a foreach loop, get the AABB of the entity and using AxisAlignedBB->calculateIntercept(), for the pos1 parameter, put the player's eye position, and for the pos2 parameter, add the eye position by their direction vector multiplied by the distance you want to traverse ($eyePos->add($directionVector->multiply(VALUE))).

    From here, I suck from explaining so enjoy some free code (I apologize for the bad formatting):

    PHP:
    $lastDist PHP_INT_MAX;
    $target null;
    foreach(
    $level->getCollidingEntities($expandedAABB) as $entity){$result $entity->getBoundingBox()->calculateIntercept($eyePos$eyePos->add($directionVector->multiply($traverseValue))); if($result !== null){if(($dist $eyePos->distance($result->getHitVector()) < $lastDist)){$lastDist $dist$target $entity;}}}
    From there, you check if the target is not null, and you are now a cool boi
    If you have any questions I'll be willing to answer them :)
     
    OguzhanUmutlu and GamakCZ like this.
  3. Moonafic

    Moonafic Silverfish

    Messages:
    24
    Thanks for help! It doesnt work if i use getCollidingEntities() as you said but if i use getNearbyEntities() it works like a charm! Thank you very much for helping!:D
     
    ethaniccc likes 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.