FishingGun.java v1.2
玩家右键使用鱼竿时发射箭
package club.scriptirc.fishinggun;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.block.Action;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
/**
* @pluginName FishingGun
* @author MPMPES
* @version 1.2
* @description 玩家右键使用鱼竿时发射箭
*/
public class FishingGunPlugin extends JavaPlugin implements Listener {
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
getLogger().info("[FishingGun] 插件已启用");
}
@Override
public void onDisable() {
getLogger().info("[FishingGun] 插件已禁用");
}
@EventHandler
public void onPlayerUseFishingRod(PlayerInteractEvent event) {
Player player = event.getPlayer();
// 仅处理主手或副手的右键
EquipmentSlot hand = event.getHand();
if (hand != EquipmentSlot.HAND && hand != EquipmentSlot.OFF_HAND) {
return;
}
// 仅处理右键点击
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
// 获取对应手的物品
ItemStack item = player.getInventory().getItem(hand);
if (item == null || item.getType() != Material.FISHING_ROD) {
return;
}
// 取消原版鱼竿事件(阻止抛线动画)
event.setCancelled(true);
// 创造模式不消耗耐久
if (player.getGameMode() == GameMode.CREATIVE) {
launchArrow(player);
return;
}
// 生存/冒险模式处理耐久消耗
handleDurability(player, item, hand);
}
/**
* 发射箭矢(核心逻辑)
*/
private void launchArrow(Player player) {
Arrow arrow = player.launchProjectile(Arrow.class, player.getLocation().getDirection().multiply(2.5));
arrow.setShooter(player);
arrow.setPickupStatus(Arrow.PickupStatus.DISALLOWED);
player.getWorld().playSound(player.getLocation(), "minecraft:entity.arrow.shoot", 1.0f, 1.2f);
}
/**
* 处理鱼竿耐久消耗(支持主副手)
*/
private void handleDurability(Player player, ItemStack item, EquipmentSlot hand) {
short durability = item.getDurability();
short maxDurability = item.getType().getMaxDurability();
// 耐久已耗尽
if (durability >= maxDurability) {
return;
}
// 消耗1点耐久
short newDurability = (short) (durability + 1);
item.setDurability(newDurability);
// 耐久耗尽时清除对应手的物品
if (newDurability >= maxDurability) {
if (hand == EquipmentSlot.HAND) {
player.getInventory().setItemInMainHand(null);
} else {
player.getInventory().setItemInOffHand(null);
}
}
// 注意:耐久未耗尽时无需重新设置物品,因为item是库存的引用
// 发射箭矢
launchArrow(player);
}
}