tweaks724/src/main/java/eu/m724/tweaks/swing/SwingManager.java
Minecon724 e59b95e2ef
All checks were successful
/ build (push) Successful in 59s
Auto swing mode
2025-01-02 20:29:59 +01:00

73 lines
2.3 KiB
Java

/*
* Copyright (C) 2025 Minecon724
* Tweaks724 is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.tweaks.swing;
import eu.m724.tweaks.DebugLogger;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SwingManager implements Listener {
private final Plugin plugin;
private final Set<Material> tools = new HashSet<>();
public SwingManager(Plugin plugin) {
this.plugin = plugin;
Arrays.stream(Material.values())
.filter(m -> m.name().contains("SWORD"))
.forEach(tools::add);
DebugLogger.fine("Tools: " + tools.size());
}
public void init() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
var type = event.getBlock().getType();
if (type.isOccluding()) return;
var player = event.getPlayer();
var tool = player.getInventory().getItemInMainHand().getType();
Entity entity = null;
if (tools.contains(tool)) { // if sword, raycast to hit farther
var result = player.getWorld().rayTraceEntities(
player.getEyeLocation(),
player.getEyeLocation().getDirection(),
player.getAttribute(Attribute.PLAYER_ENTITY_INTERACTION_RANGE).getValue(),
e -> e != player
);
if (result != null)
entity = result.getHitEntity();
} else {
entity = event.getBlock().getWorld()
.getNearbyEntities(event.getBlock().getLocation().add(0.5, 0.5, 0.5), 0.5, 0.5, 0.5)
.stream().filter(e -> (e instanceof LivingEntity && e != player))
.findFirst().orElse(null);
}
if (entity != null) {
player.attack(entity);
DebugLogger.fine("Swing " + player.getName() + " hit " + entity.getName());
}
}
}