code plugin server hoplite.gg
I need more information to create a plugin for hoplite.gg. Could you please specify:
What type of plugin do you need?
Core/hub plugin?
Minigame system?
Economy/ranking system?
Custom gameplay mechanics?
Admin tools?
What features should it include?
What’s the server theme/gamemode?
Survival/factions?
PvP arena?
Minigames network?
Greek/Spartan themed gameplay (given the “hoplite” name)?
Something else?
For example, if this is a Greek-themed server, I could create:
A class-based PvP system with Hoplite warriors
A city-state faction system
Greek mythology-themed challenges
Spartan training grounds minigame
Or if you need something more general:
A core plugin with ranks, chat formatting, and basic commands
An economy system
A custom game mode
Please provide details about what you’d like the plugin to do!
fix plugin này không bị lỗi bay thẳng lên trời cao nếu ko tìm thấy đường bay nữa
📄
legionmc_hoplite_weapon_harpoon_launcher.java
java
759 lines
▶
package org.nguyminhlong.legionMC_LegendaryWeapon.weapons;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Display;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.nguyminhlong.legionMC_Cooldowns.CooldownAPI;
import org.nguyminhlong.legionMC_LegendaryWeapon.config.weapon_config;
import org.nguyminhlong.legionMC_LegendaryWeapon.util.CooldownUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class legionmc_hoplite_weapon_harpoon_launcher implements Listener {
private final Plugin plugin;
private final weapon_config cfg;
private final CooldownAPI cooldowns;
private static final String WEAPON_ID = "harpoon_launcher";
private static final double COOLDOWN_SECONDS = 1.0;
// hook bay
private static final double MAX_TRAVEL = 100.0;
private static final double SPAWN_FORWARD = 0.75;
// chỉ scale tốc độ bay hook
private static final double INITIAL_SPEED = 2.1;
private static final double MOTION_DRAG = 0.966;
private static final double MOTION_GRAVITY = 0.022;
// kéo luôn max, không scale theo lực kéo cung
private static final double PULL_SPEED = 0.7;
private static final double RETURN_SPEED = 1.0;
private static final double TARGET_PULL_SPEED = 1.0;
private static final double FINISH_DISTANCE = 3;
// anti kẹt block khi pull
private static final double BLOCKED_HORIZONTAL_MULTIPLIER = 0.45;
private static final double BLOCKED_MIN_UPWARD = 0.42;
private static final double BLOCKED_EXTRA_UPWARD = 0.10;
// scan target lúc hook đang bay
private static final double TARGET_SCAN_RADIUS = 1.5;
// force
private static final double MIN_FORCE_TO_FIRE = 0.15;
// display
private static final Material DISPLAY_MATERIAL = Material.COMPASS;
private static final int DISPLAY_CMD = 10004;
private static final float DISPLAY_SCALE = 0.9f;
private final Map active = new ConcurrentHashMap<>();
private static final class HarpoonState {
final UUID owner;
Slime anchor;
ItemDisplay display;
boolean stuck;
boolean returning;
boolean draggingTarget;
Location stuckLocation;
double traveled;
Vector motion;
Vector lastVelocity;
LivingEntity hookedTarget;
Slime targetLeash;
double forceScale;
double scaledInitialSpeed;
boolean elytraPlaying;
HarpoonState(UUID owner, Slime anchor, ItemDisplay display, Vector initialMotion, double forceScale) {
this.owner = owner;
this.anchor = anchor;
this.display = display;
this.motion = initialMotion.clone();
this.lastVelocity = initialMotion.clone();
this.stuck = false;
this.returning = false;
this.draggingTarget = false;
this.stuckLocation = null;
this.traveled = 0.0;
this.hookedTarget = null;
this.targetLeash = null;
this.forceScale = forceScale;
this.scaledInitialSpeed = INITIAL_SPEED * forceScale;
this.elytraPlaying = false;
}
}
public legionmc_hoplite_weapon_harpoon_launcher(
Plugin plugin,
weapon_config cfg,
CooldownAPI cooldowns
) {
this.plugin = plugin;
this.cfg = cfg;
this.cooldowns = cooldowns;
new BukkitRunnable() {
@Override
public void run() {
tickHarpoons();
}
}.runTaskTimer(plugin, 1L, 1L);
}
@EventHandler
public void onShoot(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
ItemStack bow = e.getBow();
if (bow == null) return;
if (bow.getType() != Material.BOW) return;
if (!cfg.isWeapon(bow, WEAPON_ID)) return;
if (active.containsKey(p.getUniqueId())) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
if (cooldowns.has(p, WEAPON_ID)) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
float rawForce = e.getForce();
if (rawForce < MIN_FORCE_TO_FIRE) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
e.setCancelled(true);
removeProjectile(e.getProjectile());
double forceScale = Math.max(0.25, Math.min(1.0, rawForce));
spawnHarpoon(p, forceScale);
cooldowns.set(
p,
WEAPON_ID,
CooldownUtil.readFromCooldownPluginConfig(
WEAPON_ID,
COOLDOWN_SECONDS
)
);
cooldowns.setLasted(p, WEAPON_ID);
p.getWorld().playSound(
p.getEyeLocation(),
Sound.ITEM_TRIDENT_THROW,
1f,
(float) (0.9 + (rawForce * 0.2))
);
}
@EventHandler
public void onEntityUnleash(EntityUnleashEvent e) {
if (!(e.getEntity() instanceof Slime slime)) return;
for (HarpoonState s : active.values()) {
if (s.anchor != null && s.anchor.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
if (s.targetLeash != null && s.targetLeash.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
HarpoonState s = active.get(e.getPlayer().getUniqueId());
if (s != null) {
stopElytraSound(s, e.getPlayer());
}
cleanup(e.getPlayer().getUniqueId());
}
private void spawnHarpoon(Player p, double forceScale) {
Location eye = p.getEyeLocation();
Vector dir = eye.getDirection().clone().normalize();
Location spawn = eye.clone().add(dir.clone().multiply(SPAWN_FORWARD));
World w = p.getWorld();
Slime anchor = w.spawn(spawn, Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(p);
} catch (Exception ignored) {
}
});
ItemDisplay display = w.spawn(spawn, ItemDisplay.class, d -> {
d.setItemStack(buildDisplayItem());
d.setBillboard(Display.Billboard.FIXED);
d.setInterpolationDuration(1);
d.setTeleportDuration(1);
d.setPersistent(false);
d.setTransformation(new Transformation(
new Vector3f(0f, 0f, 0f),
new Quaternionf(),
new Vector3f(DISPLAY_SCALE, DISPLAY_SCALE, DISPLAY_SCALE),
new Quaternionf()
));
});
Vector initialMotion = dir.clone().multiply(INITIAL_SPEED * forceScale);
updateDisplay(display, spawn, initialMotion);
active.put(
p.getUniqueId(),
new HarpoonState(
p.getUniqueId(),
anchor,
display,
initialMotion,
forceScale
)
);
}
private void tickHarpoons() {
Iterator> it = active.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
UUID ownerId = entry.getKey();
HarpoonState s = entry.getValue();
Player p = plugin.getServer().getPlayer(ownerId);
if (p == null || !p.isOnline() || p.isDead()) {
if (p != null) {
stopElytraSound(s, p);
}
destroy(s);
it.remove();
continue;
}
if (s.draggingTarget) {
tickDragTargetToShooter(s, p, it);
continue;
}
if (s.anchor == null || !s.anchor.isValid() || s.display == null || !s.display.isValid()) {
stopElytraSound(s, p);
destroy(s);
it.remove();
continue;
}
try {
if (s.anchor.getLeashHolder() != p) {
s.anchor.setLeashHolder(p);
}
} catch (Exception ignored) {
}
if (!s.stuck && !s.returning) {
tickProjectile(s, p);
} else if (s.returning) {
tickReturn(s, p, it);
} else {
tickPull(s, p, it);
}
}
}
private void tickProjectile(HarpoonState s, Player p) {
Location from = s.anchor.getLocation();
s.motion.multiply(MOTION_DRAG);
s.motion.setY(s.motion.getY() - MOTION_GRAVITY);
double speed = s.motion.length();
if (speed <= 0.001) {
s.returning = true;
return;
}
Vector dir = s.motion.clone().normalize();
Location next = from.clone().add(s.motion);
LivingEntity target = findNearbyTarget(next, p, s);
if (target != null) {
playHookCatchSounds(p, target.getLocation());
convertHookToTargetPull(s, p, target);
return;
}
RayTraceResult hit = p.getWorld().rayTraceBlocks(
from,
dir,
speed + 0.15,
FluidCollisionMode.NEVER,
true
);
s.traveled += speed;
s.lastVelocity = s.motion.clone();
if (hit != null && hit.getHitPosition() != null) {
Location stuck = hit.getHitPosition()
.toLocation(p.getWorld())
.subtract(dir.clone().multiply(0.20));
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (next.clone().subtract(0, 0.15, 0).getBlock().getType().isSolid()) {
Location stuck = from.clone();
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (s.traveled >= MAX_TRAVEL) {
s.returning = true;
return;
}
s.anchor.teleport(next);
updateDisplay(s.display, next, s.motion);
}
private LivingEntity findNearbyTarget(Location center, Player shooter, HarpoonState s) {
Player bestPlayer = null;
double bestPlayerDist = Double.MAX_VALUE;
LivingEntity bestMob = null;
double bestMobDist = Double.MAX_VALUE;
for (Entity entity : center.getWorld().getNearbyEntities(
center,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS
)) {
if (!(entity instanceof LivingEntity living)) continue;
if (!entity.isValid()) continue;
if (entity.isDead()) continue;
if (entity.getUniqueId().equals(shooter.getUniqueId())) continue;
if (s.anchor != null && entity.getUniqueId().equals(s.anchor.getUniqueId())) continue;
if (s.display != null && entity.getUniqueId().equals(s.display.getUniqueId())) continue;
double dist = entity.getLocation().distanceSquared(center);
if (entity instanceof Player targetPlayer) {
if (!targetPlayer.isOnline()) continue;
if (dist < bestPlayerDist) {
bestPlayerDist = dist;
bestPlayer = targetPlayer;
}
continue;
}
if (dist < bestMobDist) {
bestMobDist = dist;
bestMob = living;
}
}
return bestPlayer != null ? bestPlayer : bestMob;
}
private void convertHookToTargetPull(HarpoonState s, Player shooter, LivingEntity target) {
s.draggingTarget = true;
s.hookedTarget = target;
s.returning = false;
s.stuck = false;
s.stuckLocation = null;
s.motion.zero();
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
s.display = null;
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
s.anchor = null;
Slime leashNode = shooter.getWorld().spawn(target.getLocation(), Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(shooter);
} catch (Exception ignored) {
}
});
s.targetLeash = leashNode;
s.lastVelocity = shooter.getLocation().toVector().subtract(target.getLocation().toVector());
shooter.getWorld().playSound(target.getLocation(), Sound.ENTITY_FISHING_BOBBER_RETRIEVE, 1f, 0.9f);
}
private void tickDragTargetToShooter(
HarpoonState s,
Player shooter,
Iterator> it
) {
LivingEntity target = s.hookedTarget;
Slime leashNode = s.targetLeash;
if (target == null || !target.isValid() || target.isDead()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
if (leashNode == null || !leashNode.isValid()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
try {
if (leashNode.getLeashHolder() != shooter) {
leashNode.setLeashHolder(shooter);
}
} catch (Exception ignored) {
}
Location leashLoc = target.getLocation().clone().add(0, Math.min(1.2, target.getHeight() * 0.6), 0);
leashNode.teleport(leashLoc);
Location shooterLoc = shooter.getLocation().clone().add(0, 0.3, 0);
Location targetLoc = target.getLocation().clone().add(0, 0.3, 0);
Vector toShooter = shooterLoc.toVector().subtract(targetLoc.toVector());
double dist = toShooter.length();
if (dist <= FINISH_DISTANCE) {
target.setFallDistance(0f);
stopElytraSound(s, shooter);
playFinishSound(shooter, target.getLocation());
destroy(s);
it.remove();
return;
}
Vector vel = toShooter.normalize().multiply(TARGET_PULL_SPEED);
if (toShooter.getY() > 0.05) {
vel.setY(Math.min(0.35, vel.getY() + 0.06));
}
Vector current = target.getVelocity().clone().multiply(0.2);
target.setVelocity(current.add(vel));
target.setFallDistance(0f);
}
private void tickPull(
HarpoonState s,
Player p,
Iterator> it
) {
if (s.stuckLocation == null) {
stopElytraSound(s, p);
destroy(s);
it.remove();
return;
}
Location target = s.stuckLocation.clone();
Location playerLoc = p.getLocation().clone().add(0, 0.2, 0);
Vector to = target.toVector().subtract(playerLoc.toVector());
double dist = to.length();
s.anchor.teleport(target);
updateDisplay(s.display, target, s.lastVelocity);
if (dist <= FINISH_DISTANCE) {
p.setFallDistance(0f);
stopElytraSound(s, p);
playFinishSound(p, target);
destroy(s);
it.remove();
return;
}
Vector vel = buildAntiStuckPullVelocity(playerLoc, target, p.getWorld());
Vector current = p.getVelocity().clone().multiply(0.35);
p.setVelocity(current.add(vel));
p.setFallDistance(0f);
playElytraPullSound(s, p);
}
private Vector buildAntiStuckPullVelocity(Location from, Location to, World world) {
Vector toHook = to.toVector().subtract(from.toVector());
if (toHook.lengthSquared() <= 0.0001) {
return new Vector(0, 0, 0);
}
Vector vel = toHook.clone().normalize().multiply(PULL_SPEED);
boolean blocked = isBlockedBetween(from, to, world);
if (blocked) {
vel.setX(vel.getX() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setZ(vel.getZ() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setY(Math.max(BLOCKED_MIN_UPWARD, vel.getY() + BLOCKED_EXTRA_UPWARD));
return vel;
}
if (toHook.getY() > 0.15) {
vel.setY(Math.min(0.32, vel.getY() + 0.08));
}
return vel;
}
private boolean isBlockedBetween(Location from, Location to, World world) {
Vector line = to.toVector().subtract(from.toVector());
double len = line.length();
if (len <= 0.001) {
return false;
}
RayTraceResult hit = world.rayTraceBlocks(
from,
line.normalize(),
len,
FluidCollisionMode.NEVER,
true
);
return hit != null && hit.getHitBlock() != null;
}
private void tickReturn(
HarpoonState s,
Player p,
Iterator> it
) {
Location from = s.anchor.getLocation();
Location target = p.getEyeLocation();
Vector toPlayer = target.toVector().subtract(from.toVector());
double dist = toPlayer.length();
if (dist <= 0.45) {
stopElytraSound(s, p);
playFinishSound(p, from);
destroy(s);
it.remove();
return;
}
Vector step = toPlayer.normalize().multiply(RETURN_SPEED);
Location next = from.clone().add(step);
s.anchor.teleport(next);
s.lastVelocity = step.clone();
updateDisplay(s.display, next, step);
}
private void playHookCatchSounds(Player shooter, Location hookLoc) {
World world = hookLoc.getWorld();
if (world != null) {
world.playSound(hookLoc, Sound.ITEM_TRIDENT_RETURN, 1.2f, 1.0f);
}
shooter.playSound(shooter.getLocation(), Sound.ITEM_TRIDENT_RETURN, 1.0f, 1.0f);
}
private void playElytraPullSound(HarpoonState s, Player p) {
boolean onGround = p.isOnGround()
|| p.getLocation().clone().subtract(0, 0.15, 0).getBlock().getType().isSolid();
if (onGround) {
stopElytraSound(s, p);
return;
}
if (!s.elytraPlaying) {
s.elytraPlaying = true;
p.playSound(p.getLocation(), Sound.ITEM_ELYTRA_FLYING, 0.45f, 1.05f);
}
}
private void stopElytraSound(HarpoonState s, Player p) {
s.elytraPlaying = false;
try {
p.stopSound(Sound.ITEM_ELYTRA_FLYING);
} catch (Exception ignored) {
}
}
private void playFinishSound(Player p, Location loc) {
if (loc != null && loc.getWorld() != null) {
loc.getWorld().playSound(loc, Sound.ENTITY_ITEM_PICKUP, 0.9f, 1.15f);
}
p.playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP, 0.8f, 1.2f);
}
private void updateDisplay(ItemDisplay display, Location loc, Vector dir) {
display.teleport(loc);
if (dir.lengthSquared() < 0.0001) return;
Vector n = dir.clone().normalize();
float yaw = (float) Math.toDegrees(Math.atan2(-n.getX(), n.getZ()));
float pitch = (float) Math.toDegrees(
-Math.atan2(
n.getY(),
Math.sqrt(n.getX() * n.getX() + n.getZ() * n.getZ())
)
);
display.setRotation(yaw, pitch);
}
private ItemStack buildDisplayItem() {
ItemStack item = new ItemStack(DISPLAY_MATERIAL);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setCustomModelData(DISPLAY_CMD);
item.setItemMeta(meta);
}
return item;
}
private void removeProjectile(Entity projectile) {
if (projectile != null && projectile.isValid()) {
projectile.remove();
}
}
private void cleanup(UUID playerId) {
HarpoonState s = active.remove(playerId);
if (s != null) {
destroy(s);
}
}
private void destroy(HarpoonState s) {
s.elytraPlaying = false;
try {
if (s.targetLeash != null && s.targetLeash.isValid()) {
try {
s.targetLeash.setLeashHolder(null);
} catch (Exception ignored) {
}
s.targetLeash.remove();
}
} catch (Exception ignored) {
}
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
}
}
Tôi sẽ đọc file để phân tích vấn đề bay lên trời khi không tìm thấy đường bay.
Phân tích vấn đề và giải pháp:
Vấn đề: Khi player bị kéo về hook stuck location và liên tục bị block chặn đường, code sẽ cộng dồn Y velocity (lên tới 0.52/tick), khiến player bay thẳng lên trời thay vì dừng lại.
Giải pháp:
Track số lần bị blocked liên tiếp
Nếu blocked quá nhiều lần (>12 ticks) hoặc player đã cao hơn hook location mà vẫn blocked → cancel pull
Reset counter khi không còn blocked
Các thay đổi đã thực hiện:
Thêm field
consecutiveBlockedTicksvàoHarpoonStateđể track số lần bị blocked liên tiếpThêm constants kiểm tra:
MAX_BLOCKED_TICKS = 12- Giới hạn số lần blocked liên tiếp (0.6 giây)MAX_HEIGHT_DIFFERENCE = 6.0- Giới hạn độ cao player cao hơn hook location
Cải thiện
tickPull:Tính toán
isBlockedmột lần và pass vàobuildAntiStuckPullVelocityTăng
consecutiveBlockedTickskhi bị blockedHủy pull nếu: blocked liên tiếp >12 ticks HOẶC player cao hơn hook >6 blocks
Reset counter về 0 khi không còn blocked
Update
buildAntiStuckPullVelocitynhận thêm parameterisBlockedđể tránh rayTrace 2 lần
Plugin giờ sẽ tự động hủy pull khi phát hiện player bị kẹt và bay lên trời, tránh tình trạng bay thẳng lên không kiểm soát được.
làm có thể bay đi bất cứ đâu nhưng mày thêm anti kẹt là dc
The generation was stopped before any content could be produced.
làm có thể bay đi bất cứ đâu nhưng mày thêm anti kẹt và anti bay là dc
The generation was stopped before any content could be produced.
làm có thể pull đi bất cứ đâu và ko bị hủy nhưng mày thêm anti kẹt và anti bay là dc
Tôi sẽ đọc file Harpoon Launcher hiện tại để thêm anti-stuck và anti-fly cho vũ khí này.
Tôi sẽ tạo Harpoon Launcher với khả năng pull không bị hủy, có anti-stuck và anti-fly:
Đã tạo Harpoon Launcher với các tính năng:
Tính năng chính:
Pull không bị hủy (chỉ dừng khi target chết, quá xa 50 blocks, hoặc đến gần 2 blocks)
Anti-stuck: Kiểm tra mỗi 5 ticks, nếu target không di chuyển 3 lần liên tiếp → đẩy lên trên
Anti-fly: Giới hạn độ cao tối đa 10 blocks so với mặt đất, tự động kéo xuống nếu bay quá cao
Giới hạn tốc độ Y tối đa 0.5 để tránh bay quá cao
Reset fall damage để tránh target chết khi bị pull
làm có thể pull đi bất cứ đâu và ko bị hủy nhưng mày thêm anti kẹt và anti bay là dc
📄
legionmc_hoplite_weapon_harpoon_launcher.java
java
783 lines
▶
package org.nguyminhlong.legionMC_LegendaryWeapon.weapons;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Display;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.nguyminhlong.legionMC_Cooldowns.CooldownAPI;
import org.nguyminhlong.legionMC_LegendaryWeapon.config.weapon_config;
import org.nguyminhlong.legionMC_LegendaryWeapon.util.CooldownUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class legionmc_hoplite_weapon_harpoon_launcher implements Listener {
private final Plugin plugin;
private final weapon_config cfg;
private final CooldownAPI cooldowns;
private static final String WEAPON_ID = "harpoon_launcher";
private static final double COOLDOWN_SECONDS = 1.0;
private static final double MAX_TRAVEL = 100.0;
private static final double SPAWN_FORWARD = 0.75;
private static final double INITIAL_SPEED = 2.1;
private static final double MOTION_DRAG = 0.966;
private static final double MOTION_GRAVITY = 0.022;
private static final double PULL_SPEED = 0.7;
private static final double RETURN_SPEED = 1.0;
private static final double TARGET_PULL_SPEED = 1.0;
private static final double FINISH_DISTANCE = 3;
private static final double BLOCKED_HORIZONTAL_MULTIPLIER = 0.45;
private static final double BLOCKED_MIN_UPWARD = 0.42;
private static final double BLOCKED_EXTRA_UPWARD = 0.10;
private static final double TARGET_SCAN_RADIUS = 1.5;
private static final double MIN_FORCE_TO_FIRE = 0.15;
private static final Material DISPLAY_MATERIAL = Material.COMPASS;
private static final int DISPLAY_CMD = 10004;
private static final float DISPLAY_SCALE = 0.9f;
private static final int MAX_BLOCKED_TICKS = 12;
private static final double MAX_HEIGHT_DIFFERENCE = 6.0;
private final Map active = new ConcurrentHashMap<>();
private static final class HarpoonState {
final UUID owner;
Slime anchor;
ItemDisplay display;
boolean stuck;
boolean returning;
boolean draggingTarget;
Location stuckLocation;
double traveled;
Vector motion;
Vector lastVelocity;
LivingEntity hookedTarget;
Slime targetLeash;
double forceScale;
double scaledInitialSpeed;
boolean elytraPlaying;
int consecutiveBlockedTicks;
HarpoonState(UUID owner, Slime anchor, ItemDisplay display, Vector initialMotion, double forceScale) {
this.owner = owner;
this.anchor = anchor;
this.display = display;
this.motion = initialMotion.clone();
this.lastVelocity = initialMotion.clone();
this.stuck = false;
this.returning = false;
this.draggingTarget = false;
this.stuckLocation = null;
this.traveled = 0.0;
this.hookedTarget = null;
this.targetLeash = null;
this.forceScale = forceScale;
this.scaledInitialSpeed = INITIAL_SPEED * forceScale;
this.elytraPlaying = false;
this.consecutiveBlockedTicks = 0;
}
}
public legionmc_hoplite_weapon_harpoon_launcher(
Plugin plugin,
weapon_config cfg,
CooldownAPI cooldowns
) {
this.plugin = plugin;
this.cfg = cfg;
this.cooldowns = cooldowns;
new BukkitRunnable() {
@Override
public void run() {
tickHarpoons();
}
}.runTaskTimer(plugin, 1L, 1L);
}
@EventHandler
public void onShoot(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
ItemStack bow = e.getBow();
if (bow == null) return;
if (bow.getType() != Material.BOW) return;
if (!cfg.isWeapon(bow, WEAPON_ID)) return;
if (active.containsKey(p.getUniqueId())) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
if (cooldowns.has(p, WEAPON_ID)) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
float rawForce = e.getForce();
if (rawForce < MIN_FORCE_TO_FIRE) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
e.setCancelled(true);
removeProjectile(e.getProjectile());
double forceScale = Math.max(0.25, Math.min(1.0, rawForce));
spawnHarpoon(p, forceScale);
cooldowns.set(
p,
WEAPON_ID,
CooldownUtil.readFromCooldownPluginConfig(
WEAPON_ID,
COOLDOWN_SECONDS
)
);
cooldowns.setLasted(p, WEAPON_ID);
p.getWorld().playSound(
p.getEyeLocation(),
Sound.ITEM_TRIDENT_THROW,
1f,
(float) (0.9 + (rawForce * 0.2))
);
}
@EventHandler
public void onEntityUnleash(EntityUnleashEvent e) {
if (!(e.getEntity() instanceof Slime slime)) return;
for (HarpoonState s : active.values()) {
if (s.anchor != null && s.anchor.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
if (s.targetLeash != null && s.targetLeash.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
HarpoonState s = active.get(e.getPlayer().getUniqueId());
if (s != null) {
stopElytraSound(s, e.getPlayer());
}
cleanup(e.getPlayer().getUniqueId());
}
private void spawnHarpoon(Player p, double forceScale) {
Location eye = p.getEyeLocation();
Vector dir = eye.getDirection().clone().normalize();
Location spawn = eye.clone().add(dir.clone().multiply(SPAWN_FORWARD));
World w = p.getWorld();
Slime anchor = w.spawn(spawn, Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(p);
} catch (Exception ignored) {
}
});
ItemDisplay display = w.spawn(spawn, ItemDisplay.class, d -> {
d.setItemStack(buildDisplayItem());
d.setBillboard(Display.Billboard.FIXED);
d.setInterpolationDuration(1);
d.setTeleportDuration(1);
d.setPersistent(false);
d.setTransformation(new Transformation(
new Vector3f(0f, 0f, 0f),
new Quaternionf(),
new Vector3f(DISPLAY_SCALE, DISPLAY_SCALE, DISPLAY_SCALE),
new Quaternionf()
));
});
Vector initialMotion = dir.clone().multiply(INITIAL_SPEED * forceScale);
updateDisplay(display, spawn, initialMotion);
active.put(
p.getUniqueId(),
new HarpoonState(
p.getUniqueId(),
anchor,
display,
initialMotion,
forceScale
)
);
}
private void tickHarpoons() {
Iterator> it = active.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
UUID ownerId = entry.getKey();
HarpoonState s = entry.getValue();
Player p = plugin.getServer().getPlayer(ownerId);
if (p == null || !p.isOnline() || p.isDead()) {
if (p != null) {
stopElytraSound(s, p);
}
destroy(s);
it.remove();
continue;
}
if (s.draggingTarget) {
tickDragTargetToShooter(s, p, it);
continue;
}
if (s.anchor == null || !s.anchor.isValid() || s.display == null || !s.display.isValid()) {
stopElytraSound(s, p);
destroy(s);
it.remove();
continue;
}
try {
if (s.anchor.getLeashHolder() != p) {
s.anchor.setLeashHolder(p);
}
} catch (Exception ignored) {
}
if (!s.stuck && !s.returning) {
tickProjectile(s, p);
} else if (s.returning) {
tickReturn(s, p, it);
} else {
tickPull(s, p, it);
}
}
}
private void tickProjectile(HarpoonState s, Player p) {
Location from = s.anchor.getLocation();
s.motion.multiply(MOTION_DRAG);
s.motion.setY(s.motion.getY() - MOTION_GRAVITY);
double speed = s.motion.length();
if (speed <= 0.001) {
s.returning = true;
return;
}
Vector dir = s.motion.clone().normalize();
Location next = from.clone().add(s.motion);
LivingEntity target = findNearbyTarget(next, p, s);
if (target != null) {
playHookCatchSounds(p, target.getLocation());
convertHookToTargetPull(s, p, target);
return;
}
RayTraceResult hit = p.getWorld().rayTraceBlocks(
from,
dir,
speed + 0.15,
FluidCollisionMode.NEVER,
true
);
s.traveled += speed;
s.lastVelocity = s.motion.clone();
if (hit != null && hit.getHitPosition() != null) {
Location stuck = hit.getHitPosition()
.toLocation(p.getWorld())
.subtract(dir.clone().multiply(0.20));
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (next.clone().subtract(0, 0.15, 0).getBlock().getType().isSolid()) {
Location stuck = from.clone();
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (s.traveled >= MAX_TRAVEL) {
s.returning = true;
return;
}
s.anchor.teleport(next);
updateDisplay(s.display, next, s.motion);
}
private LivingEntity findNearbyTarget(Location center, Player shooter, HarpoonState s) {
Player bestPlayer = null;
double bestPlayerDist = Double.MAX_VALUE;
LivingEntity bestMob = null;
double bestMobDist = Double.MAX_VALUE;
for (Entity entity : center.getWorld().getNearbyEntities(
center,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS
)) {
if (!(entity instanceof LivingEntity living)) continue;
if (!entity.isValid()) continue;
if (entity.isDead()) continue;
if (entity.getUniqueId().equals(shooter.getUniqueId())) continue;
if (s.anchor != null && entity.getUniqueId().equals(s.anchor.getUniqueId())) continue;
if (s.display != null && entity.getUniqueId().equals(s.display.getUniqueId())) continue;
double dist = entity.getLocation().distanceSquared(center);
if (entity instanceof Player targetPlayer) {
if (!targetPlayer.isOnline()) continue;
if (dist < bestPlayerDist) {
bestPlayerDist = dist;
bestPlayer = targetPlayer;
}
continue;
}
if (dist < bestMobDist) {
bestMobDist = dist;
bestMob = living;
}
}
return bestPlayer != null ? bestPlayer : bestMob;
}
private void convertHookToTargetPull(HarpoonState s, Player shooter, LivingEntity target) {
s.draggingTarget = true;
s.hookedTarget = target;
s.returning = false;
s.stuck = false;
s.stuckLocation = null;
s.motion.zero();
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
s.display = null;
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
s.anchor = null;
Slime leashNode = shooter.getWorld().spawn(target.getLocation(), Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(shooter);
} catch (Exception ignored) {
}
});
s.targetLeash = leashNode;
s.lastVelocity = shooter.getLocation().toVector().subtract(target.getLocation().toVector());
shooter.getWorld().playSound(target.getLocation(), Sound.ENTITY_FISHING_BOBBER_RETRIEVE, 1f, 0.9f);
}
private void tickDragTargetToShooter(
HarpoonState s,
Player shooter,
Iterator> it
) {
LivingEntity target = s.hookedTarget;
Slime leashNode = s.targetLeash;
if (target == null || !target.isValid() || target.isDead()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
if (leashNode == null || !leashNode.isValid()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
try {
if (leashNode.getLeashHolder() != shooter) {
leashNode.setLeashHolder(shooter);
}
} catch (Exception ignored) {
}
Location leashLoc = target.getLocation().clone().add(0, Math.min(1.2, target.getHeight() * 0.6), 0);
leashNode.teleport(leashLoc);
Location shooterLoc = shooter.getLocation().clone().add(0, 0.3, 0);
Location targetLoc = target.getLocation().clone().add(0, 0.3, 0);
Vector toShooter = shooterLoc.toVector().subtract(targetLoc.toVector());
double dist = toShooter.length();
if (dist <= FINISH_DISTANCE) {
target.setFallDistance(0f);
stopElytraSound(s, shooter);
playFinishSound(shooter, target.getLocation());
destroy(s);
it.remove();
return;
}
Vector vel = toShooter.normalize().multiply(TARGET_PULL_SPEED);
if (toShooter.getY() > 0.05) {
vel.setY(Math.min(0.35, vel.getY() + 0.06));
}
Vector current = target.getVelocity().clone().multiply(0.2);
target.setVelocity(current.add(vel));
target.setFallDistance(0f);
}
private void tickPull(
HarpoonState s,
Player p,
Iterator> it
) {
if (s.stuckLocation == null) {
stopElytraSound(s, p);
destroy(s);
it.remove();
return;
}
Location target = s.stuckLocation.clone();
Location playerLoc = p.getLocation().clone().add(0, 0.2, 0);
Vector to = target.toVector().subtract(playerLoc.toVector());
double dist = to.length();
s.anchor.teleport(target);
updateDisplay(s.display, target, s.lastVelocity);
if (dist <= FINISH_DISTANCE) {
p.setFallDistance(0f);
stopElytraSound(s, p);
playFinishSound(p, target);
destroy(s);
it.remove();
return;
}
boolean isBlocked = isBlockedBetween(playerLoc, target, p.getWorld());
if (isBlocked) {
s.consecutiveBlockedTicks++;
double heightDiff = playerLoc.getY() - target.getY();
if (s.consecutiveBlockedTicks > MAX_BLOCKED_TICKS) {
p.setFallDistance(0f);
stopElytraSound(s, p);
destroy(s);
it.remove();
return;
}
if (heightDiff > MAX_HEIGHT_DIFFERENCE) {
p.setFallDistance(0f);
stopElytraSound(s, p);
destroy(s);
it.remove();
return;
}
} else {
s.consecutiveBlockedTicks = 0;
}
Vector vel = buildAntiStuckPullVelocity(playerLoc, target, p.getWorld(), isBlocked);
Vector current = p.getVelocity().clone().multiply(0.35);
p.setVelocity(current.add(vel));
p.setFallDistance(0f);
playElytraPullSound(s, p);
}
private Vector buildAntiStuckPullVelocity(Location from, Location to, World world, boolean isBlocked) {
Vector toHook = to.toVector().subtract(from.toVector());
if (toHook.lengthSquared() <= 0.0001) {
return new Vector(0, 0, 0);
}
Vector vel = toHook.clone().normalize().multiply(PULL_SPEED);
if (isBlocked) {
vel.setX(vel.getX() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setZ(vel.getZ() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setY(Math.max(BLOCKED_MIN_UPWARD, vel.getY() + BLOCKED_EXTRA_UPWARD));
return vel;
}
if (toHook.getY() > 0.15) {
vel.setY(Math.min(0.32, vel.getY() + 0.08));
}
return vel;
}
private boolean isBlockedBetween(Location from, Location to, World world) {
Vector line = to.toVector().subtract(from.toVector());
double len = line.length();
if (len <= 0.001) {
return false;
}
RayTraceResult hit = world.rayTraceBlocks(
from,
line.normalize(),
len,
FluidCollisionMode.NEVER,
true
);
return hit != null && hit.getHitBlock() != null;
}
private void tickReturn(
HarpoonState s,
Player p,
Iterator> it
) {
Location from = s.anchor.getLocation();
Location target = p.getEyeLocation();
Vector toPlayer = target.toVector().subtract(from.toVector());
double dist = toPlayer.length();
if (dist <= 0.45) {
stopElytraSound(s, p);
playFinishSound(p, from);
destroy(s);
it.remove();
return;
}
Vector step = toPlayer.normalize().multiply(RETURN_SPEED);
Location next = from.clone().add(step);
s.anchor.teleport(next);
s.lastVelocity = step.clone();
updateDisplay(s.display, next, step);
}
private void playHookCatchSounds(Player shooter, Location hookLoc) {
World world = hookLoc.getWorld();
if (world != null) {
world.playSound(hookLoc, Sound.ITEM_TRIDENT_RETURN, 1.2f, 1.0f);
}
shooter.playSound(shooter.getLocation(), Sound.ITEM_TRIDENT_RETURN, 1.0f, 1.0f);
}
private void playElytraPullSound(HarpoonState s, Player p) {
boolean onGround = p.isOnGround()
|| p.getLocation().clone().subtract(0, 0.15, 0).getBlock().getType().isSolid();
if (onGround) {
stopElytraSound(s, p);
return;
}
if (!s.elytraPlaying) {
s.elytraPlaying = true;
p.playSound(p.getLocation(), Sound.ITEM_ELYTRA_FLYING, 0.45f, 1.05f);
}
}
private void stopElytraSound(HarpoonState s, Player p) {
s.elytraPlaying = false;
try {
p.stopSound(Sound.ITEM_ELYTRA_FLYING);
} catch (Exception ignored) {
}
}
private void playFinishSound(Player p, Location loc) {
if (loc != null && loc.getWorld() != null) {
loc.getWorld().playSound(loc, Sound.ENTITY_ITEM_PICKUP, 0.9f, 1.15f);
}
p.playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP, 0.8f, 1.2f);
}
private void updateDisplay(ItemDisplay display, Location loc, Vector dir) {
display.teleport(loc);
if (dir.lengthSquared() < 0.0001) return;
Vector n = dir.clone().normalize();
float yaw = (float) Math.toDegrees(Math.atan2(-n.getX(), n.getZ()));
float pitch = (float) Math.toDegrees(
-Math.atan2(
n.getY(),
Math.sqrt(n.getX() * n.getX() + n.getZ() * n.getZ())
)
);
display.setRotation(yaw, pitch);
}
private ItemStack buildDisplayItem() {
ItemStack item = new ItemStack(DISPLAY_MATERIAL);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setCustomModelData(DISPLAY_CMD);
item.setItemMeta(meta);
}
return item;
}
private void removeProjectile(Entity projectile) {
if (projectile != null && projectile.isValid()) {
projectile.remove();
}
}
private void cleanup(UUID playerId) {
HarpoonState s = active.remove(playerId);
if (s != null) {
destroy(s);
}
}
private void destroy(HarpoonState s) {
s.elytraPlaying = false;
try {
if (s.targetLeash != null && s.targetLeash.isValid()) {
try {
s.targetLeash.setLeashHolder(null);
} catch (Exception ignored) {
}
s.targetLeash.remove();
}
} catch (Exception ignored) {
}
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
}
}
Tôi sẽ cải thiện harpoon launcher với:
Bỏ giới hạn blocked ticks và height difference (pull được mọi nơi)
Anti-stuck: tự động phát hiện kẹt và teleport lên
Anti-fly: giới hạn velocity để không bay quá cao
Đã cải thiện harpoon launcher với:
✅ Pull được mọi nơi không bị hủy: Bỏ hết giới hạn MAX_BLOCKED_TICKS và MAX_HEIGHT_DIFFERENCE
✅ Anti-kẹt mạnh mẽ:
Track vị trí player mỗi 8 ticks
Phát hiện kẹt khi di chuyển < 0.25 blocks
Sau 4 lần check stuck → tự động teleport player tới vị trí an toàn gần hook
Tăng upward force khi bị blocked (0.55 thay vì 0.42)
✅ Anti-bay chặt chẽ:
Giới hạn Y velocity tối đa 0.75 (không bay quá cao)
Thêm downward force 0.08 khi đang trên không
Check ground để apply gravity tự nhiên
Velocity được balance để pull mượt nhưng không bay loạn
làm nếu bị kẹt thì cancel ngay và fix bay vô hạn lên trời huhu
📄
legionmc_hoplite_weapon_harpoon_launcher.java
java
855 lines
▶
package org.nguyminhlong.legionMC_LegendaryWeapon.weapons;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Display;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.nguyminhlong.legionMC_Cooldowns.CooldownAPI;
import org.nguyminhlong.legionMC_LegendaryWeapon.config.weapon_config;
import org.nguyminhlong.legionMC_LegendaryWeapon.util.CooldownUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class legionmc_hoplite_weapon_harpoon_launcher implements Listener {
private final Plugin plugin;
private final weapon_config cfg;
private final CooldownAPI cooldowns;
private static final String WEAPON_ID = "harpoon_launcher";
private static final double COOLDOWN_SECONDS = 1.0;
private static final double MAX_TRAVEL = 100.0;
private static final double SPAWN_FORWARD = 0.75;
private static final double INITIAL_SPEED = 2.1;
private static final double MOTION_DRAG = 0.966;
private static final double MOTION_GRAVITY = 0.022;
private static final double PULL_SPEED = 0.7;
private static final double RETURN_SPEED = 1.0;
private static final double TARGET_PULL_SPEED = 1.0;
private static final double FINISH_DISTANCE = 3;
private static final double BLOCKED_HORIZONTAL_MULTIPLIER = 0.35;
private static final double BLOCKED_MIN_UPWARD = 0.55;
private static final double BLOCKED_EXTRA_UPWARD = 0.15;
private static final double TARGET_SCAN_RADIUS = 1.5;
private static final double MIN_FORCE_TO_FIRE = 0.15;
private static final Material DISPLAY_MATERIAL = Material.COMPASS;
private static final int DISPLAY_CMD = 10004;
private static final float DISPLAY_SCALE = 0.9f;
private static final int STUCK_CHECK_INTERVAL = 8;
private static final double STUCK_THRESHOLD = 0.25;
private static final int STUCK_TELEPORT_THRESHOLD = 4;
private static final double ANTI_FLY_MAX_Y_VELOCITY = 0.75;
private static final double ANTI_FLY_DOWNWARD_FORCE = 0.08;
private final Map active = new ConcurrentHashMap<>();
private static final class HarpoonState {
final UUID owner;
Slime anchor;
ItemDisplay display;
boolean stuck;
boolean returning;
boolean draggingTarget;
Location stuckLocation;
double traveled;
Vector motion;
Vector lastVelocity;
LivingEntity hookedTarget;
Slime targetLeash;
double forceScale;
double scaledInitialSpeed;
boolean elytraPlaying;
Location lastPlayerLocation;
int playerStuckCounter;
int ticksSinceStuckCheck;
HarpoonState(UUID owner, Slime anchor, ItemDisplay display, Vector initialMotion, double forceScale) {
this.owner = owner;
this.anchor = anchor;
this.display = display;
this.motion = initialMotion.clone();
this.lastVelocity = initialMotion.clone();
this.stuck = false;
this.returning = false;
this.draggingTarget = false;
this.stuckLocation = null;
this.traveled = 0.0;
this.hookedTarget = null;
this.targetLeash = null;
this.forceScale = forceScale;
this.scaledInitialSpeed = INITIAL_SPEED * forceScale;
this.elytraPlaying = false;
this.lastPlayerLocation = null;
this.playerStuckCounter = 0;
this.ticksSinceStuckCheck = 0;
}
}
public legionmc_hoplite_weapon_harpoon_launcher(
Plugin plugin,
weapon_config cfg,
CooldownAPI cooldowns
) {
this.plugin = plugin;
this.cfg = cfg;
this.cooldowns = cooldowns;
new BukkitRunnable() {
@Override
public void run() {
tickHarpoons();
}
}.runTaskTimer(plugin, 1L, 1L);
}
@EventHandler
public void onShoot(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
ItemStack bow = e.getBow();
if (bow == null) return;
if (bow.getType() != Material.BOW) return;
if (!cfg.isWeapon(bow, WEAPON_ID)) return;
if (active.containsKey(p.getUniqueId())) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
if (cooldowns.has(p, WEAPON_ID)) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
float rawForce = e.getForce();
if (rawForce < MIN_FORCE_TO_FIRE) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
e.setCancelled(true);
removeProjectile(e.getProjectile());
double forceScale = Math.max(0.25, Math.min(1.0, rawForce));
spawnHarpoon(p, forceScale);
cooldowns.set(
p,
WEAPON_ID,
CooldownUtil.readFromCooldownPluginConfig(
WEAPON_ID,
COOLDOWN_SECONDS
)
);
cooldowns.setLasted(p, WEAPON_ID);
p.getWorld().playSound(
p.getEyeLocation(),
Sound.ITEM_TRIDENT_THROW,
1f,
(float) (0.9 + (rawForce * 0.2))
);
}
@EventHandler
public void onEntityUnleash(EntityUnleashEvent e) {
if (!(e.getEntity() instanceof Slime slime)) return;
for (HarpoonState s : active.values()) {
if (s.anchor != null && s.anchor.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
if (s.targetLeash != null && s.targetLeash.getUniqueId().equals(slime.getUniqueId())) {
e.setCancelled(true);
return;
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
HarpoonState s = active.get(e.getPlayer().getUniqueId());
if (s != null) {
stopElytraSound(s, e.getPlayer());
}
cleanup(e.getPlayer().getUniqueId());
}
private void spawnHarpoon(Player p, double forceScale) {
Location eye = p.getEyeLocation();
Vector dir = eye.getDirection().clone().normalize();
Location spawn = eye.clone().add(dir.clone().multiply(SPAWN_FORWARD));
World w = p.getWorld();
Slime anchor = w.spawn(spawn, Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(p);
} catch (Exception ignored) {
}
});
ItemDisplay display = w.spawn(spawn, ItemDisplay.class, d -> {
d.setItemStack(buildDisplayItem());
d.setBillboard(Display.Billboard.FIXED);
d.setInterpolationDuration(1);
d.setTeleportDuration(1);
d.setPersistent(false);
d.setTransformation(new Transformation(
new Vector3f(0f, 0f, 0f),
new Quaternionf(),
new Vector3f(DISPLAY_SCALE, DISPLAY_SCALE, DISPLAY_SCALE),
new Quaternionf()
));
});
Vector initialMotion = dir.clone().multiply(INITIAL_SPEED * forceScale);
updateDisplay(display, spawn, initialMotion);
active.put(
p.getUniqueId(),
new HarpoonState(
p.getUniqueId(),
anchor,
display,
initialMotion,
forceScale
)
);
}
private void tickHarpoons() {
Iterator> it = active.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
UUID ownerId = entry.getKey();
HarpoonState s = entry.getValue();
Player p = plugin.getServer().getPlayer(ownerId);
if (p == null || !p.isOnline() || p.isDead()) {
if (p != null) {
stopElytraSound(s, p);
}
destroy(s);
it.remove();
continue;
}
if (s.draggingTarget) {
tickDragTargetToShooter(s, p, it);
continue;
}
if (s.anchor == null || !s.anchor.isValid() || s.display == null || !s.display.isValid()) {
stopElytraSound(s, p);
destroy(s);
it.remove();
continue;
}
try {
if (s.anchor.getLeashHolder() != p) {
s.anchor.setLeashHolder(p);
}
} catch (Exception ignored) {
}
if (!s.stuck && !s.returning) {
tickProjectile(s, p);
} else if (s.returning) {
tickReturn(s, p, it);
} else {
tickPull(s, p, it);
}
}
}
private void tickProjectile(HarpoonState s, Player p) {
Location from = s.anchor.getLocation();
s.motion.multiply(MOTION_DRAG);
s.motion.setY(s.motion.getY() - MOTION_GRAVITY);
double speed = s.motion.length();
if (speed <= 0.001) {
s.returning = true;
return;
}
Vector dir = s.motion.clone().normalize();
Location next = from.clone().add(s.motion);
LivingEntity target = findNearbyTarget(next, p, s);
if (target != null) {
playHookCatchSounds(p, target.getLocation());
convertHookToTargetPull(s, p, target);
return;
}
RayTraceResult hit = p.getWorld().rayTraceBlocks(
from,
dir,
speed + 0.15,
FluidCollisionMode.NEVER,
true
);
s.traveled += speed;
s.lastVelocity = s.motion.clone();
if (hit != null && hit.getHitPosition() != null) {
Location stuck = hit.getHitPosition()
.toLocation(p.getWorld())
.subtract(dir.clone().multiply(0.20));
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (next.clone().subtract(0, 0.15, 0).getBlock().getType().isSolid()) {
Location stuck = from.clone();
s.stuck = true;
s.stuckLocation = stuck.clone();
s.anchor.teleport(stuck);
s.motion.zero();
updateDisplay(s.display, stuck, s.lastVelocity);
playHookCatchSounds(p, stuck);
return;
}
if (s.traveled >= MAX_TRAVEL) {
s.returning = true;
return;
}
s.anchor.teleport(next);
updateDisplay(s.display, next, s.motion);
}
private LivingEntity findNearbyTarget(Location center, Player shooter, HarpoonState s) {
Player bestPlayer = null;
double bestPlayerDist = Double.MAX_VALUE;
LivingEntity bestMob = null;
double bestMobDist = Double.MAX_VALUE;
for (Entity entity : center.getWorld().getNearbyEntities(
center,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS,
TARGET_SCAN_RADIUS
)) {
if (!(entity instanceof LivingEntity living)) continue;
if (!entity.isValid()) continue;
if (entity.isDead()) continue;
if (entity.getUniqueId().equals(shooter.getUniqueId())) continue;
if (s.anchor != null && entity.getUniqueId().equals(s.anchor.getUniqueId())) continue;
if (s.display != null && entity.getUniqueId().equals(s.display.getUniqueId())) continue;
double dist = entity.getLocation().distanceSquared(center);
if (entity instanceof Player targetPlayer) {
if (!targetPlayer.isOnline()) continue;
if (dist < bestPlayerDist) {
bestPlayerDist = dist;
bestPlayer = targetPlayer;
}
continue;
}
if (dist < bestMobDist) {
bestMobDist = dist;
bestMob = living;
}
}
return bestPlayer != null ? bestPlayer : bestMob;
}
private void convertHookToTargetPull(HarpoonState s, Player shooter, LivingEntity target) {
s.draggingTarget = true;
s.hookedTarget = target;
s.returning = false;
s.stuck = false;
s.stuckLocation = null;
s.motion.zero();
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
s.display = null;
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
s.anchor = null;
Slime leashNode = shooter.getWorld().spawn(target.getLocation(), Slime.class, slime -> {
slime.setAI(false);
slime.setInvisible(true);
slime.setInvulnerable(true);
slime.setSilent(true);
slime.setCollidable(false);
slime.setGravity(false);
slime.setSize(1);
slime.setPersistent(false);
slime.setRemoveWhenFarAway(false);
try {
slime.setLeashHolder(shooter);
} catch (Exception ignored) {
}
});
s.targetLeash = leashNode;
s.lastVelocity = shooter.getLocation().toVector().subtract(target.getLocation().toVector());
shooter.getWorld().playSound(target.getLocation(), Sound.ENTITY_FISHING_BOBBER_RETRIEVE, 1f, 0.9f);
}
private void tickDragTargetToShooter(
HarpoonState s,
Player shooter,
Iterator> it
) {
LivingEntity target = s.hookedTarget;
Slime leashNode = s.targetLeash;
if (target == null || !target.isValid() || target.isDead()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
if (leashNode == null || !leashNode.isValid()) {
stopElytraSound(s, shooter);
destroy(s);
it.remove();
return;
}
try {
if (leashNode.getLeashHolder() != shooter) {
leashNode.setLeashHolder(shooter);
}
} catch (Exception ignored) {
}
Location leashLoc = target.getLocation().clone().add(0, Math.min(1.2, target.getHeight() * 0.6), 0);
leashNode.teleport(leashLoc);
Location shooterLoc = shooter.getLocation().clone().add(0, 0.3, 0);
Location targetLoc = target.getLocation().clone().add(0, 0.3, 0);
Vector toShooter = shooterLoc.toVector().subtract(targetLoc.toVector());
double dist = toShooter.length();
if (dist <= FINISH_DISTANCE) {
target.setFallDistance(0f);
stopElytraSound(s, shooter);
playFinishSound(shooter, target.getLocation());
destroy(s);
it.remove();
return;
}
Vector vel = toShooter.normalize().multiply(TARGET_PULL_SPEED);
if (toShooter.getY() > 0.05) {
vel.setY(Math.min(0.45, vel.getY() + 0.08));
}
if (vel.getY() > ANTI_FLY_MAX_Y_VELOCITY) {
vel.setY(ANTI_FLY_MAX_Y_VELOCITY);
}
Vector current = target.getVelocity().clone().multiply(0.2);
target.setVelocity(current.add(vel));
target.setFallDistance(0f);
}
private void tickPull(
HarpoonState s,
Player p,
Iterator> it
) {
if (s.stuckLocation == null) {
stopElytraSound(s, p);
destroy(s);
it.remove();
return;
}
Location target = s.stuckLocation.clone();
Location playerLoc = p.getLocation().clone().add(0, 0.2, 0);
Vector to = target.toVector().subtract(playerLoc.toVector());
double dist = to.length();
s.anchor.teleport(target);
updateDisplay(s.display, target, s.lastVelocity);
if (dist <= FINISH_DISTANCE) {
p.setFallDistance(0f);
stopElytraSound(s, p);
playFinishSound(p, target);
destroy(s);
it.remove();
return;
}
checkAndHandlePlayerStuck(s, p, target);
boolean isBlocked = isBlockedBetween(playerLoc, target, p.getWorld());
Vector vel = buildAntiStuckPullVelocity(playerLoc, target, p.getWorld(), isBlocked);
if (vel.getY() > ANTI_FLY_MAX_Y_VELOCITY) {
vel.setY(ANTI_FLY_MAX_Y_VELOCITY);
}
Location groundCheck = playerLoc.clone().subtract(0, 1, 0);
if (!groundCheck.getBlock().getType().isSolid() && !p.isOnGround()) {
vel.setY(vel.getY() - ANTI_FLY_DOWNWARD_FORCE);
}
Vector current = p.getVelocity().clone().multiply(0.35);
p.setVelocity(current.add(vel));
p.setFallDistance(0f);
playElytraPullSound(s, p);
}
private void checkAndHandlePlayerStuck(HarpoonState s, Player p, Location hookLoc) {
s.ticksSinceStuckCheck++;
if (s.ticksSinceStuckCheck < STUCK_CHECK_INTERVAL) {
return;
}
s.ticksSinceStuckCheck = 0;
Location currentLoc = p.getLocation();
if (s.lastPlayerLocation == null) {
s.lastPlayerLocation = currentLoc.clone();
return;
}
double moved = s.lastPlayerLocation.distance(currentLoc);
if (moved < STUCK_THRESHOLD) {
s.playerStuckCounter++;
if (s.playerStuckCounter >= STUCK_TELEPORT_THRESHOLD) {
handleStuckTeleport(s, p, hookLoc);
s.playerStuckCounter = 0;
}
} else {
s.playerStuckCounter = 0;
}
s.lastPlayerLocation = currentLoc.clone();
}
private void handleStuckTeleport(HarpoonState s, Player p, Location hookLoc) {
Location playerLoc = p.getLocation();
Vector toHook = hookLoc.toVector().subtract(playerLoc.toVector());
double distToHook = toHook.length();
if (distToHook < 2.0) {
return;
}
Location safeSpot = findSafeTeleportSpot(playerLoc, hookLoc);
if (safeSpot != null) {
p.teleport(safeSpot);
p.getWorld().playSound(p.getLocation(), Sound.ENTITY_ENDERMAN_TELEPORT, 0.5f, 1.5f);
}
}
private Location findSafeTeleportSpot(Location from, Location to) {
Vector direction = to.toVector().subtract(from.toVector()).normalize();
for (double distance = 2.0; distance <= 8.0; distance += 1.0) {
Location test = from.clone().add(direction.clone().multiply(distance));
Location feet = test.clone();
Location head = test.clone().add(0, 1, 0);
Location ground = test.clone().subtract(0, 1, 0);
if (!feet.getBlock().getType().isSolid() &&
!head.getBlock().getType().isSolid() &&
ground.getBlock().getType().isSolid()) {
return test;
}
}
Location upTest = from.clone().add(0, 2, 0);
if (!upTest.getBlock().getType().isSolid() &&
!upTest.clone().add(0, 1, 0).getBlock().getType().isSolid()) {
return upTest;
}
return null;
}
private Vector buildAntiStuckPullVelocity(Location from, Location to, World world, boolean isBlocked) {
Vector toHook = to.toVector().subtract(from.toVector());
if (toHook.lengthSquared() <= 0.0001) {
return new Vector(0, 0, 0);
}
Vector vel = toHook.clone().normalize().multiply(PULL_SPEED);
if (isBlocked) {
vel.setX(vel.getX() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setZ(vel.getZ() * BLOCKED_HORIZONTAL_MULTIPLIER);
vel.setY(Math.max(BLOCKED_MIN_UPWARD, vel.getY() + BLOCKED_EXTRA_UPWARD));
return vel;
}
if (toHook.getY() > 0.15) {
vel.setY(Math.min(0.40, vel.getY() + 0.10));
}
return vel;
}
private boolean isBlockedBetween(Location from, Location to, World world) {
Vector line = to.toVector().subtract(from.toVector());
double len = line.length();
if (len <= 0.001) {
return false;
}
RayTraceResult hit = world.rayTraceBlocks(
from,
line.normalize(),
len,
FluidCollisionMode.NEVER,
true
);
return hit != null && hit.getHitBlock() != null;
}
private void tickReturn(
HarpoonState s,
Player p,
Iterator> it
) {
Location from = s.anchor.getLocation();
Location target = p.getEyeLocation();
Vector toPlayer = target.toVector().subtract(from.toVector());
double dist = toPlayer.length();
if (dist <= 0.45) {
stopElytraSound(s, p);
playFinishSound(p, from);
destroy(s);
it.remove();
return;
}
Vector step = toPlayer.normalize().multiply(RETURN_SPEED);
Location next = from.clone().add(step);
s.anchor.teleport(next);
s.lastVelocity = step.clone();
updateDisplay(s.display, next, step);
}
private void playHookCatchSounds(Player shooter, Location hookLoc) {
World world = hookLoc.getWorld();
if (world != null) {
world.playSound(hookLoc, Sound.ITEM_TRIDENT_RETURN, 1.2f, 1.0f);
}
shooter.playSound(shooter.getLocation(), Sound.ITEM_TRIDENT_RETURN, 1.0f, 1.0f);
}
private void playElytraPullSound(HarpoonState s, Player p) {
boolean onGround = p.isOnGround()
|| p.getLocation().clone().subtract(0, 0.15, 0).getBlock().getType().isSolid();
if (onGround) {
stopElytraSound(s, p);
return;
}
if (!s.elytraPlaying) {
s.elytraPlaying = true;
p.playSound(p.getLocation(), Sound.ITEM_ELYTRA_FLYING, 0.45f, 1.05f);
}
}
private void stopElytraSound(HarpoonState s, Player p) {
s.elytraPlaying = false;
try {
p.stopSound(Sound.ITEM_ELYTRA_FLYING);
} catch (Exception ignored) {
}
}
private void playFinishSound(Player p, Location loc) {
if (loc != null && loc.getWorld() != null) {
loc.getWorld().playSound(loc, Sound.ENTITY_ITEM_PICKUP, 0.9f, 1.15f);
}
p.playSound(p.getLocation(), Sound.ENTITY_ITEM_PICKUP, 0.8f, 1.2f);
}
private void updateDisplay(ItemDisplay display, Location loc, Vector dir) {
display.teleport(loc);
if (dir.lengthSquared() < 0.0001) return;
Vector n = dir.clone().normalize();
float yaw = (float) Math.toDegrees(Math.atan2(-n.getX(), n.getZ()));
float pitch = (float) Math.toDegrees(
-Math.atan2(
n.getY(),
Math.sqrt(n.getX() * n.getX() + n.getZ() * n.getZ())
)
);
display.setRotation(yaw, pitch);
}
private ItemStack buildDisplayItem() {
ItemStack item = new ItemStack(DISPLAY_MATERIAL);
ItemMeta meta = item.getItemMeta();
if (meta != null) {
meta.setCustomModelData(DISPLAY_CMD);
item.setItemMeta(meta);
}
return item;
}
private void removeProjectile(Entity projectile) {
if (projectile != null && projectile.isValid()) {
projectile.remove();
}
}
private void cleanup(UUID playerId) {
HarpoonState s = active.remove(playerId);
if (s != null) {
destroy(s);
}
}
private void destroy(HarpoonState s) {
s.elytraPlaying = false;
try {
if (s.targetLeash != null && s.targetLeash.isValid()) {
try {
s.targetLeash.setLeashHolder(null);
} catch (Exception ignored) {
}
s.targetLeash.remove();
}
} catch (Exception ignored) {
}
try {
if (s.anchor != null && s.anchor.isValid()) {
try {
s.anchor.setLeashHolder(null);
} catch (Exception ignored) {
}
s.anchor.remove();
}
} catch (Exception ignored) {
}
try {
if (s.display != null && s.display.isValid()) {
s.display.remove();
}
} catch (Exception ignored) {
}
}
}
I’ll analyze and fix the infinite flying and stuck issues in the harpoon launcher. Let me read the necessary files first.
I’ll fix the infinite flying and stuck issues. The main problems are:
Stuck detection is too slow (8 ticks × 4 checks = 32 ticks)
Downward force is too weak (0.08 isn’t enough)
No height limit check (players can fly infinitely upward)
No timeout for being stuck
Fixed Issues:
Faster stuck detection: 3 ticks × 2 checks = 6 ticks (0.3s) instead of 32 ticks
Stronger downward force: Increased from 0.08 to 0.25 to prevent infinite flying
Height limit: Cancels if player goes 12 blocks above hook
Stuck timeout: Cancels after 60 ticks (3 seconds) of being stuck
Failed teleport limit: Cancels after 3 failed teleport attempts
Better velocity handling: Reduces momentum multiplier in air (0.2 vs 0.35)
Y velocity capping: Max upward 0.50, max downward -1.5
Teleport resets velocity: Prevents momentum carry-over
User feedback: Shows messages when cancelled
The harpoon now cancels immediately when detecting issues and prevents infinite upward flight!
mày code thay cái display item cưỡi bóng tuyết bằng display item velocity dc k và giữ nguyên logic bay hướng các thứ của cái cũ
📄
pasted-code-1774107258495.txt
txt
380 lines
▶
package org.nguyminhlong.legionMC_LegendaryWeapon.weapons;
import org.bukkit.*;
import org.bukkit.entity.Display;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Interaction;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class legionmc_hoplite_weapon_aiglos implements Listener {
private final Plugin plugin;
private static final int AIGLOS_CMD = 10006;
private static final float FULL_DRAW_MIN = 0.99f;
private static final double OUT_STEP_BASE = 2.6;
private static final double OUT_STEP_FORCE_BONUS = 1.2;
private static final double OUT_STEP_MIN = 2.1;
private static final double OUT_STEP_MAX = 2.8;
private static final int OUT_MAX_TICKS = 50;
private static final Material DISPLAY_ITEM = Material.BOW;
private static final int DISPLAY_CMD = 10006;
private static final float TRANSFORM_ROT_X_DEG = 90f;
private static final float HITBOX_W = 0.35f;
private static final float HITBOX_H = 0.35f;
private static final double ENTITY_HIT_RADIUS = 0.35;
private static final int DISPLAY_INTERP_DURATION = 1;
private static final int DISPLAY_TELEPORT_DURATION = 1;
private static final float EXPLOSION_POWER = 6.5f;
private final Map active = new ConcurrentHashMap<>();
private static final class AiglosState {
final UUID owner;
final Interaction hitbox;
final ItemDisplay display;
final Vector dir;
final double outStep;
int ageTicks = 0;
final ItemStack removedItem;
AiglosState(UUID owner, Interaction hitbox, ItemDisplay display, Vector dir, double outStep, ItemStack removedItem) {
this.owner = owner;
this.hitbox = hitbox;
this.display = display;
this.dir = dir;
this.outStep = outStep;
this.removedItem = removedItem;
}
}
public legionmc_hoplite_weapon_aiglos(Plugin plugin) {
this.plugin = plugin;
new BukkitRunnable() {
@Override
public void run() {
aiglos_tick();
}
}.runTaskTimer(plugin, 1L, 1L);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void aiglos_onShoot(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
ItemStack bow = e.getBow();
if (!aiglos_isItem(bow, AIGLOS_CMD)) return;
if (aiglos_hasActiveFor(p.getUniqueId())) {
e.setCancelled(true);
p.playSound(p.getLocation(), Sound.UI_BUTTON_CLICK, 0.3f, 0.7f);
return;
}
float force = e.getForce();
if (force < FULL_DRAW_MIN) {
e.setCancelled(true);
p.playSound(p.getLocation(), Sound.UI_BUTTON_CLICK, 0.3f, 0.8f);
return;
}
e.setCancelled(true);
if (e.getProjectile() != null && e.getProjectile().isValid()) {
e.getProjectile().remove();
}
double outStep = aiglos_computeOutStep(force);
EquipmentSlot hand = aiglos_resolveHand(e, p, bow);
ItemStack removed = aiglos_removeFromHand(p, hand);
aiglos_spawnProjectile(p, outStep, removed);
}
private boolean aiglos_hasActiveFor(UUID playerId) {
for (AiglosState st : active.values()) {
if (st != null && playerId.equals(st.owner)) return true;
}
return false;
}
private static EquipmentSlot aiglos_resolveHand(EntityShootBowEvent e, Player p, ItemStack bow) {
try {
EquipmentSlot slot = e.getHand();
if (slot != null) return slot;
} catch (Throwable ignored) {
}
PlayerInventory inv = p.getInventory();
ItemStack main = inv.getItemInMainHand();
if (main != null && main.isSimilar(bow)) return EquipmentSlot.HAND;
ItemStack off = inv.getItemInOffHand();
if (off != null && off.isSimilar(bow)) return EquipmentSlot.OFF_HAND;
return EquipmentSlot.HAND;
}
private static ItemStack aiglos_removeFromHand(Player p, EquipmentSlot hand) {
PlayerInventory inv = p.getInventory();
ItemStack cur = (hand == EquipmentSlot.OFF_HAND) ? inv.getItemInOffHand() : inv.getItemInMainHand();
if (cur == null || cur.getType() == Material.AIR) return null;
ItemStack saved = cur.clone();
if (hand == EquipmentSlot.OFF_HAND) {
inv.setItemInOffHand(new ItemStack(Material.AIR));
} else {
inv.setItemInMainHand(new ItemStack(Material.AIR));
}
p.updateInventory();
return saved;
}
private static double aiglos_computeOutStep(float force) {
double f = Math.max(0.0, Math.min(1.0, force));
double s = OUT_STEP_BASE + (f * OUT_STEP_FORCE_BONUS);
if (s < OUT_STEP_MIN) s = OUT_STEP_MIN;
if (s > OUT_STEP_MAX) s = OUT_STEP_MAX;
return s;
}
private void aiglos_spawnProjectile(Player p, double outStep, ItemStack removedItem) {
Location eye = p.getEyeLocation();
Vector dir = eye.getDirection().normalize();
Location spawnAt = eye.clone().add(dir.clone().multiply(0.4));
World w = spawnAt.getWorld();
if (w == null) return;
Interaction hit = (Interaction) w.spawnEntity(spawnAt, EntityType.INTERACTION);
hit.setInteractionWidth(HITBOX_W);
hit.setInteractionHeight(HITBOX_H);
hit.setResponsive(false);
ItemDisplay disp = (ItemDisplay) w.spawnEntity(spawnAt, EntityType.ITEM_DISPLAY);
disp.setBillboard(Display.Billboard.FIXED);
disp.setItemStack(aiglos_makeDisplayItem(DISPLAY_ITEM, DISPLAY_CMD));
disp.setTransformation(new Transformation(
new Vector3f(0f, 0f, 0f),
new Quaternionf().rotationX((float) Math.toRadians(TRANSFORM_ROT_X_DEG)),
new Vector3f(1f, 1f, 1f),
new Quaternionf()
));
try {
disp.setInterpolationDuration(DISPLAY_INTERP_DURATION);
} catch (Throwable ignored) {
}
try {
disp.setTeleportDuration(DISPLAY_TELEPORT_DURATION);
} catch (Throwable ignored) {
}
aiglos_applyRotationFromDir(disp, dir);
AiglosState st = new AiglosState(p.getUniqueId(), hit, disp, dir, outStep, removedItem);
active.put(hit.getUniqueId(), st);
w.playSound(p.getLocation(), Sound.ITEM_TRIDENT_THROW, 0.9f, 1.1f);
}
private void aiglos_tick() {
if (active.isEmpty()) return;
Iterator> it = active.entrySet().iterator();
while (it.hasNext()) {
AiglosState st = it.next().getValue();
if (st.hitbox == null || !st.hitbox.isValid() || st.display == null || !st.display.isValid()) {
aiglos_cleanup(st);
it.remove();
continue;
}
Player owner = Bukkit.getPlayer(st.owner);
if (owner == null || !owner.isOnline()) {
aiglos_cleanup(st);
it.remove();
continue;
}
st.ageTicks++;
if (st.ageTicks >= OUT_MAX_TICKS) {
aiglos_finish(owner, st.hitbox.getLocation(), st);
it.remove();
continue;
}
Location cur = st.hitbox.getLocation();
World w = cur.getWorld();
if (w == null) {
aiglos_finish(owner, owner.getLocation(), st);
it.remove();
continue;
}
Vector step = st.dir.clone().multiply(st.outStep);
Location next = cur.clone().add(step);
Vector rayVec = next.toVector().subtract(cur.toVector());
double rayLen = rayVec.length();
Vector rayDir = (rayLen > 1e-8) ? rayVec.clone().multiply(1.0 / rayLen) : st.dir;
RayTraceResult blockHit = w.rayTraceBlocks(cur, rayDir, rayLen, FluidCollisionMode.NEVER, true);
if (blockHit != null && blockHit.getHitBlock() != null) {
Location impact = blockHit.getHitPosition().toLocation(w);
aiglos_finish(owner, impact, st);
it.remove();
continue;
}
LivingEntity hitEnt = aiglos_findHitEntity(owner, cur, next);
if (hitEnt != null) {
Location impact = hitEnt.getLocation().add(0, hitEnt.getHeight() * 0.6, 0);
aiglos_finish(owner, impact, st);
it.remove();
continue;
}
aiglos_teleportPair(st, next);
aiglos_applyRotationFromDir(st.display, st.dir);
}
}
private void aiglos_finish(Player owner, Location impact, AiglosState st) {
World w = impact.getWorld();
if (w != null) {
w.createExplosion(impact.getX(), impact.getY(), impact.getZ(), EXPLOSION_POWER, false, true);
w.playSound(impact, Sound.ENTITY_GENERIC_EXPLODE, 1.0f, 1.0f);
}
aiglos_cleanup(st);
if (owner != null && owner.isOnline()) {
aiglos_giveBack(owner, st.removedItem);
}
}
private LivingEntity aiglos_findHitEntity(Player owner, Location cur, Location next) {
World w = cur.getWorld();
if (w == null) return null;
BoundingBox sweep = BoundingBox.of(cur, next).expand(ENTITY_HIT_RADIUS);
for (Entity e : w.getNearbyEntities(sweep)) {
if (!(e instanceof LivingEntity le)) continue;
if (!le.isValid() || le.isDead()) continue;
if (le.getUniqueId().equals(owner.getUniqueId())) continue;
if (le.getBoundingBox().overlaps(sweep)) return le;
}
return null;
}
private void aiglos_teleportPair(AiglosState st, Location to) {
st.hitbox.teleport(to);
st.display.teleport(to);
}
private void aiglos_applyRotationFromDir(ItemDisplay disp, Vector dir) {
if (dir == null || dir.lengthSquared() < 1e-8) return;
Vector d = dir.clone().normalize();
Location tmp = disp.getLocation();
tmp.setDirection(d);
disp.setRotation(tmp.getYaw(), tmp.getPitch());
}
private void aiglos_cleanup(AiglosState st) {
try {
if (st.display != null && st.display.isValid()) st.display.remove();
} catch (Throwable ignored) {
}
try {
if (st.hitbox != null && st.hitbox.isValid()) st.hitbox.remove();
} catch (Throwable ignored) {
}
}
private static void aiglos_giveBack(Player p, ItemStack item) {
if (item == null || item.getType() == Material.AIR) return;
PlayerInventory inv = p.getInventory();
ItemStack main = inv.getItemInMainHand();
if (main == null || main.getType() == Material.AIR) {
inv.setItemInMainHand(item);
p.updateInventory();
return;
}
for (int slot = 0; slot <= 8; slot++) {
ItemStack hotbarItem = inv.getItem(slot);
if (hotbarItem == null || hotbarItem.getType() == Material.AIR) {
inv.setItem(slot, item);
p.updateInventory();
return;
}
}
HashMap left = inv.addItem(item);
p.updateInventory();
if (!left.isEmpty()) {
for (ItemStack remain : left.values()) {
p.getWorld().dropItemNaturally(p.getLocation().add(0, 1.0, 0), remain);
}
}
}
private static boolean aiglos_isItem(ItemStack it, int cmd) {
if (it == null || it.getType() != Material.BOW) return false;
ItemMeta meta = it.getItemMeta();
return meta != null && meta.hasCustomModelData() && meta.getCustomModelData() == cmd;
}
private static ItemStack aiglos_makeDisplayItem(Material mat, int cmd) {
ItemStack it = new ItemStack(mat);
ItemMeta meta = it.getItemMeta();
if (meta != null) {
meta.setCustomModelData(cmd);
it.setItemMeta(meta);
}
return it;
}
}
package org.nguyminhlong.legionMC_LegendaryWeapon.weapons;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Display;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Transformation;
import org.bukkit.util.Vector;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import org.nguyminhlong.legionMC_Cooldowns.CooldownAPI;
import org.nguyminhlong.legionMC_LegendaryWeapon.config.weapon_config;
import org.nguyminhlong.legionMC_LegendaryWeapon.util.CooldownUtil;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public final class legionmc_hoplite_weapon_harpoon_launcher implements Listener {
private final Plugin plugin;
private final weapon_config cfg;
private final CooldownAPI cooldowns;
private static final String WEAPON_ID = "harpoon_launcher";
private static final double COOLDOWN_SECONDS = 1.0;
private static final double MAX_TRAVEL = 100.0;
private static final double SPAWN_FORWARD = 0.75;
private static final double INITIAL_SPEED = 2.1;
private static final double MOTION_DRAG = 0.966;
private static final double MOTION_GRAVITY = 0.022;
private static final double PULL_SPEED = 0.7;
private static final double RETURN_SPEED = 1.0;
private static final double TARGET_PULL_SPEED = 1.0;
private static final double FINISH_DISTANCE = 3;
private static final double BLOCKED_HORIZONTAL_MULTIPLIER = 0.35;
private static final double BLOCKED_MIN_UPWARD = 0.55;
private static final double BLOCKED_EXTRA_UPWARD = 0.15;
private static final double TARGET_SCAN_RADIUS = 1.5;
private static final double MIN_FORCE_TO_FIRE = 0.15;
private static final Material DISPLAY_MATERIAL = Material.COMPASS;
private static final int DISPLAY_CMD = 10004;
private static final float DISPLAY_SCALE = 0.9f;
private static final int STUCK_CHECK_INTERVAL = 8;
private static final double STUCK_THRESHOLD = 0.25;
private static final int STUCK_TELEPORT_THRESHOLD = 4;
private static final double ANTI_FLY_MAX_Y_VELOCITY = 0.75;
private static final double ANTI_FLY_DOWNWARD_FORCE = 0.08;
private final Map<UUID, HarpoonState> active = new ConcurrentHashMap<>();
private static final class HarpoonState {
final UUID owner;
Slime anchor;
ItemDisplay display;
boolean stuck;
boolean returning;
boolean draggingTarget;
Location stuckLocation;
double traveled;
Vector motion;
Vector lastVelocity;
LivingEntity hookedTarget;
Slime targetLeash;
double forceScale;
double scaledInitialSpeed;
boolean elytraPlaying;
Location lastPlayerLocation;
int playerStuckCounter;
int ticksSinceStuckCheck;
HarpoonState(UUID owner, Slime anchor, ItemDisplay display, Vector initialMotion, double forceScale) {
this.owner = owner;
this.anchor = anchor;
this.display = display;
this.motion = initialMotion.clone();
this.lastVelocity = initialMotion.clone();
this.stuck = false;
this.returning = false;
this.draggingTarget = false;
this.stuckLocation = null;
this.traveled = 0.0;
this.hookedTarget = null;
this.targetLeash = null;
this.forceScale = forceScale;
this.scaledInitialSpeed = INITIAL_SPEED * forceScale;
this.elytraPlaying = false;
this.lastPlayerLocation = null;
this.playerStuckCounter = 0;
this.ticksSinceStuckCheck = 0;
}
}
public legionmc_hoplite_weapon_harpoon_launcher(
Plugin plugin,
weapon_config cfg,
CooldownAPI cooldowns
) {
this.plugin = plugin;
this.cfg = cfg;
this.cooldowns = cooldowns;
new BukkitRunnable() {
@Override
public void run() {
tickHarpoons();
}
}.runTaskTimer(plugin, 1L, 1L);
}
@EventHandler
public void onShoot(EntityShootBowEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
ItemStack bow = e.getBow();
if (bow == null) return;
if (bow.getType() != Material.BOW) return;
if (!cfg.isWeapon(bow, WEAPON_ID)) return;
if (active.containsKey(p.getUniqueId())) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
if (cooldowns.has(p, WEAPON_ID)) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
float rawForce = e.getForce();
if (rawForce < MIN_FORCE_TO_FIRE) {
e.setCancelled(true);
removeProjectile(e.getProjectile());
return;
}
e.setCancelled(true);
removeProjectile(e.getProjectile());
double forceScale = Math.max(0.25, Math.min(1.0, rawForce));
spawnHarpoon(p, forceScale);
cooldowns.set(
p,
WEAPON_ID,
CooldownUtil.readFromCooldownPluginConfig(
WEAPON_ID,
COOLDOWN_SECONDS
)
);
cooldowns.setLasted(p, WEAPON_ID);
p.getWorld().playSound(
p.getEyeLocation(),
Sound.ITEM_TRIDENT_THROW,
1f,
(float) (0.9 + (rawForce * 0.2))
);