Skip to content

Instantly share code, notes, and snippets.

@mtbarr
Created October 12, 2020 11:58
Show Gist options
  • Save mtbarr/7d1cf2b904c51f87dc130041865dacf8 to your computer and use it in GitHub Desktop.
Save mtbarr/7d1cf2b904c51f87dc130041865dacf8 to your computer and use it in GitHub Desktop.
package io.github.sasuke.newvalencia.core.tooling.nms.combat;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.EnumWrappers.EntityUseAction;
import io.github.sasuke.newvalencia.core.CorePlugin;
import io.github.sasuke.newvalencia.core.tooling.event.async.AsyncPlayerPreDamageEntityEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import static com.comphenix.protocol.PacketType.Play.Client.USE_ENTITY;
import static com.comphenix.protocol.PacketType.Play.Server.ENTITY_STATUS;
public class AsyncHitDetectionListener extends PacketAdapter {
private static final float MAX_DISTANCE = (float) 3.85 * (float) 3.85;
public AsyncHitDetectionListener() {
super(CorePlugin.getInstance(), USE_ENTITY);
}
@Override
public void onPacketReceiving(PacketEvent event) {
if (event.getPacketType() != USE_ENTITY) {
return;
}
PacketContainer packet = event.getPacket();
Player player = event.getPlayer();
Entity entity = packet.getEntityModifier(event).read(0);
if (!(entity instanceof Damageable)) {
return;
}
if (player.getLocation().distanceSquared(entity.getLocation()) > MAX_DISTANCE) {
return;
}
if (!player.getWorld().getName().equalsIgnoreCase(entity.getWorld().getName())) {
return;
}
EntityUseAction action = packet.getEntityUseActions().read(0);
if (action != EntityUseAction.ATTACK) {
return;
}
AsyncPlayerPreDamageEntityEvent preDamageEntityEvent = new AsyncPlayerPreDamageEntityEvent(
player,
entity
);
Bukkit.getPluginManager().callEvent(preDamageEntityEvent);
if (!preDamageEntityEvent.isCancelled()) {
sendDamageAnimation(player, entity.getEntityId());
}
}
private void sendDamageAnimation(Player player, int entityId) {
PacketContainer damagePacket = new PacketContainer(ENTITY_STATUS);
damagePacket.getIntegers().write(0, entityId);
damagePacket.getBytes().write(0, (byte) 2);
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(player, damagePacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment