Starchasers / OCGlasses

mod for minecraft and addon for Open Computers
zlib License
30 stars 17 forks source link

[Suggestion] Make getUserLookingAt returns which entity the player is looking at #109

Open fan87 opened 2 years ago

fan87 commented 2 years ago

Is your feature request related to a problem? Please describe. No

Describe the solution you'd like Make getUserLookingAt returns which entity the player is facing. Right now it only has 2 types: block and air, if there's entity it should be great

Describe alternatives you've considered I don't know

Additional context I'm going through the OpenGlasses' source, and saw the todo:

//todo: figure out entity raytracing on server side, probably did that already in OpenEntity

at Line 650, OpenGlassesHostComponent.java

Bukkit seems to have a that does entity ray tracing, you can probably use that:

    @Override
    public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate<Entity> filter) {
        Validate.notNull(start, "Start location is null!");
        Validate.isTrue(this.equals(start.getWorld()), "Start location is from different world!");
        start.checkFinite();

        Validate.notNull(direction, "Direction is null!");
        direction.checkFinite();

        Validate.isTrue(direction.lengthSquared() > 0, "Direction's magnitude is 0!");

        if (maxDistance < 0.0D) {
            return null;
        }

        Vector startPos = start.toVector();
        Vector dir = direction.clone().normalize().multiply(maxDistance);
        BoundingBox aabb = BoundingBox.of(startPos, startPos).expandDirectional(dir).expand(raySize);
        Collection<Entity> entities = this.getNearbyEntities(aabb, filter);

        Entity nearestHitEntity = null;
        RayTraceResult nearestHitResult = null;
        double nearestDistanceSq = Double.MAX_VALUE;

        for (Entity entity : entities) {
            BoundingBox boundingBox = entity.getBoundingBox().expand(raySize);
            RayTraceResult hitResult = boundingBox.rayTrace(startPos, direction, maxDistance);

            if (hitResult != null) {
                double distanceSq = startPos.distanceSquared(hitResult.getHitPosition());

                if (distanceSq < nearestDistanceSq) {
                    nearestHitEntity = entity;
                    nearestHitResult = hitResult;
                    nearestDistanceSq = distanceSq;
                }
            }
        }

        return (nearestHitEntity == null) ? null : new RayTraceResult(nearestHitResult.getHitPosition(), nearestHitEntity, nearestHitResult.getHitBlockFace());
    }

(Source: CraftWorld.java) Well, it's wrapped by custom classes, so you may have to remap it manually to MCP's mapping