Created
October 12, 2020 11:58
-
-
Save mtbarr/7d1cf2b904c51f87dc130041865dacf8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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