Files
src
Code
3 158
src/main/java/com/verity/event/VerityEventHandler.java
package com.verity.event;
import com.verity.client.VerityScreen;
import com.verity.entity.VerityEntity;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.fabricmc.fabric.api.event.player.AttackEntityCallback;
import net.fabricmc.fabric.api.event.player.UseEntityCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.api.EnvType;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.math.Vec3d;
public final class VerityEventHandler {
private static final long FLASH_DURATION_MILLIS = 300L;
private static volatile long flashUntilMillis;
private VerityEventHandler() {
}
public static void register() {
AttackEntityCallback.EVENT.register((player, world, hand, target, hitResult) -> {
if (!(target instanceof VerityEntity)) {
return ActionResult.PASS;
}
if (world.isClient) {
world.playSound(null, target.getX(), target.getY(), target.getZ(),
SoundEvents.ENTITY_GHAST_SCREAM, SoundCategory.HOSTILE, 2.0F, 0.65F);
flashUntilMillis = System.currentTimeMillis() + FLASH_DURATION_MILLIS;
} else {
teleportAway(target, player);
}
return ActionResult.PASS;
});
UseEntityCallback.EVENT.register((player, world, hand, target, hitResult) -> {
if (!(target instanceof VerityEntity)) {
return ActionResult.PASS;
}
if (world.isClient) {
MinecraftClient.getInstance().setScreen(new VerityScreen());
}
return ActionResult.SUCCESS;
});
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
HudRenderCallback.EVENT.register((drawContext, tickCounter) -> {
long remaining = flashUntilMillis - System.currentTimeMillis();
if (remaining <= 0L) {
return;
}
int alpha = (int) (190 * remaining / FLASH_DURATION_MILLIS);
drawContext.fill(0, 0, drawContext.getScaledWindowWidth(),
drawContext.getScaledWindowHeight(), alpha << 24);
});
}
}
private static void teleportAway(Entity entity, Entity player) {
Vec3d away = entity.getPos().subtract(player.getPos());
Vec3d horizontal = new Vec3d(away.x, 0.0, away.z);
if (horizontal.lengthSquared() < 1.0E-6) {
horizontal = new Vec3d(1.0, 0.0, 0.0);
} else {
horizontal = horizontal.normalize();
}
Vec3d destination = player.getPos().add(horizontal.multiply(20.0))
.add(0.0, entity.getY() - player.getY(), 0.0);
entity.refreshPositionAndAngles(destination.x, destination.y, destination.z,
entity.getYaw(), entity.getPitch());
}
}