Passed
Branch dev (d24a17)
by Etienne
01:34
created

de.kleiner3.lasertag.common.util.RaycastUtil   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
dl 0
loc 39
rs 10
c 0
b 0
f 0
eloc 16

1 Method

Rating   Name   Duplication   Size   Complexity  
A raycastCrosshair(PlayerEntity,int) 0 33 3
1
package de.kleiner3.lasertag.common.util;
2
3
import net.minecraft.entity.player.PlayerEntity;
4
import net.minecraft.entity.projectile.ProjectileUtil;
5
import net.minecraft.util.hit.BlockHitResult;
6
import net.minecraft.util.hit.EntityHitResult;
7
import net.minecraft.util.hit.HitResult;
8
import net.minecraft.util.math.Box;
9
import net.minecraft.util.math.Vec3d;
10
import net.minecraft.world.RaycastContext;
11
12
/**
13
 * Utility class to do Raycasting
14
 *
15
 * @author Étiennne Muser
16
 */
17
public class RaycastUtil {
18
    /**
19
     * Raycasts into the direction of the crosshair
20
     *
21
     * @return The HitResult of the raycast
22
     */
23
    public static HitResult raycastCrosshair(PlayerEntity playerEntity, int maxDistance) {
24
25
        // Get the cameras position to start the raycasting from
26
        Vec3d startPos = playerEntity.getCameraPosVec(1.0f);
27
28
        // Get the cameras direction vector to raycast in that direction
29
        Vec3d direction = playerEntity.getRotationVec(1.0f);
30
31
        // Lengthen the direction vector to match maxDistance
32
        Vec3d ray = startPos.add(direction.x * maxDistance, direction.y * maxDistance, direction.z * maxDistance);
33
34
        // Do the block-raycast (ignore fluids) and return the result
35
        BlockHitResult blockHit = playerEntity.world.raycast(new RaycastContext(startPos, ray, RaycastContext.ShapeType.OUTLINE, RaycastContext.FluidHandling.NONE, playerEntity));
36
37
        Box box = playerEntity
38
                .getBoundingBox()
39
                .stretch(playerEntity.getRotationVec(1.0F).multiply(maxDistance))
40
                .expand(1.0D, 1.0D, 1.0D);
41
42
        // Do the entity-raycast
43
        EntityHitResult entityhit = ProjectileUtil.raycast(playerEntity, startPos, ray, box, entity -> !entity.isSpectator(), Double.MAX_VALUE);
44
45
        // If no entity was hit
46
        if (entityhit == null) {
47
            return blockHit;
48
        }
49
50
        // If entity is closer than block
51
        if (startPos.squaredDistanceTo(entityhit.getPos()) < startPos.squaredDistanceTo(blockHit.getPos())) {
52
            return entityhit;
53
        }
54
55
        return blockHit;
56
    }
57
}
58