Getting Entity Player is Looking At?

I’m trying to write code that will damage an entity that a player is looking at.

For example, if I am staring at a cow, then the cow takes damage.

I know how to damage a player, so all I need is to know how to get the entity that the player is looking at.


Util there is an api for bounding boxes you have use BlockRay.

I think there isn’t a “EntityRotationEvent”. So you have to check in a task scheduled with the scheduler. There you use BlockRay.

There is however DisplaceEntityEvent.Move, which is fired when an entity moves. For players it’s DisplaceEntityEvent.Move.TargetPlayer. However, I’m not sure which of these are implemented.

Yes, I know. But I don’t know whether it is fired if the player only rotates. I think it shouldn’t because of the naming “Displace”, so place and not general moving.

DisplaceEntityEvent.Move.TargetPlayer is a perfect parallel to Bukkit’s PlayerMoveEvent (but with a better name), it will fire in that case.

Ok, then the docs aren’t good:

Called when an {@link Entity} changes position (also known as undergoing displacement).

I think that rotating counts as changing position

Not intuitive to me.

Using BlockRay:

Optional<BlockRayHit<World>> optHit = BlockRay.from(player).filter(BlockRay.onlyAirFilter()).build().end();
if (optHit.isPresent()) {
    Vector3d lookPos = optHit.get().getBlockPosition().toDouble();
    Collection<Entity> entities = player.getWorld().getEntities(entity -> entity != player && entity.getLocation().getPosition().distanceSquared(lookPos) < 4);

You can set a maximum distance to test for by using blockLimit(total), the default is 1000 blocks.

1 Like

Ok. Thank you guys!