Generalizes the ray tracing used for finding the portal a player is looking at

This commit is contained in:
2022-05-31 03:54:51 +02:00
parent 347a08c0e9
commit 382b84869f
2 changed files with 41 additions and 12 deletions

View File

@@ -5,12 +5,11 @@ import net.TheDgtl.Stargate.manager.PermissionManager;
import net.TheDgtl.Stargate.network.Network;
import net.TheDgtl.Stargate.network.RegistryAPI;
import net.TheDgtl.Stargate.network.portal.RealPortal;
import org.bukkit.Location;
import net.knarcraft.stargatecommand.util.PortalFinderHelper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
/**
@@ -65,16 +64,7 @@ public class CommandDial implements CommandExecutor {
}
//Find any Stargate block in the player's line of sight
RealPortal originPortal = null;
Location playerLocation = player.getLocation().add(0, player.getEyeHeight(), 0);
Vector playerDirection = player.getLocation().getDirection();
for (int i = 0; i < 10; i++) {
playerLocation.add(playerDirection);
originPortal = registryAPI.getPortal(playerLocation);
if (originPortal != null) {
break;
}
}
RealPortal originPortal = (RealPortal) PortalFinderHelper.findPortalByRaytrace(registryAPI, player, 10);
if (originPortal == null) {
player.sendMessage("You need to look at a portal to dial");
return true;

View File

@@ -0,0 +1,39 @@
package net.knarcraft.stargatecommand.util;
import net.TheDgtl.Stargate.network.RegistryAPI;
import net.TheDgtl.Stargate.network.portal.Portal;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.util.Vector;
/**
* A helper class for helping with finding portals in the world
*/
public class PortalFinderHelper {
/**
* Find the portal a living entity is looking at using a single traced ray
*
* @param registryAPI <p>The registry used for looking up portals</p>
* @param livingEntity <p>The living entity to ray trace from</p>
* @param rayLength <p>The maximum length of the ray before giving up</p>
* @return <p>The portal the player is looking at, or null if no portal was found</p>
*/
public static Portal findPortalByRaytrace(RegistryAPI registryAPI, LivingEntity livingEntity, int rayLength) {
Location entityLocation = livingEntity.getLocation().add(0, livingEntity.getEyeHeight(), 0);
Vector entityDirection = livingEntity.getLocation().getDirection();
Portal foundPortal = null;
//Follow the ray outwards from the entity until a portal is found
for (int i = 0; i < rayLength; i++) {
entityLocation.add(entityDirection);
foundPortal = registryAPI.getPortal(entityLocation);
//Stop if a portal is found. Also, don't trace through solid blocks.
if (foundPortal != null || !entityLocation.getBlock().getType().isAir()) {
break;
}
}
return foundPortal;
}
}