Files
backstab_fabric_mod
Code
6 201
backstab_fabric_mod/src/main/java/com/kodari/backstab/BackstabMod.java
package com.kodari.backstab;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.player.AttackEntityCallback;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
public final class BackstabMod implements ModInitializer {
private static final float BONUS_DAMAGE = 6.0F;
private static final double REAR_CONE_DOT = -0.5D;
@Override
public void onInitialize() {
AttackEntityCallback.EVENT.register((player, world, hand, entity, hitResult) -> {
if (world.isClient()
|| !(world instanceof ServerWorld serverWorld)
|| !(entity instanceof LivingEntity target)
|| player.getAttackCooldownProgress(0.5F) < 0.9F
|| !isBehind(player, target)) {
return ActionResult.PASS;
}
if (!target.damage(serverWorld, serverWorld.getDamageSources().playerAttack(player), BONUS_DAMAGE)) {
return ActionResult.PASS;
}
serverWorld.spawnParticles(
ParticleTypes.CRIT,
target.getX(),
target.getBodyY(0.5D),
target.getZ(),
24,
0.45D,
0.65D,
0.45D,
0.2D
);
serverWorld.playSound(
null,
target.getBlockPos(),
SoundEvents.ENTITY_PLAYER_ATTACK_CRIT,
SoundCategory.PLAYERS,
1.0F,
1.15F
);
if (player instanceof ServerPlayerEntity serverPlayer) {
serverPlayer.sendMessage(Text.literal("BACKSTAB!"), true);
}
return ActionResult.PASS;
});
}
private static boolean isBehind(PlayerEntity attacker, LivingEntity target) {
Vec3d directionToAttacker = attacker.getPos().subtract(target.getPos());
Vec3d horizontalDirection = new Vec3d(directionToAttacker.x, 0.0D, directionToAttacker.z);
if (horizontalDirection.lengthSquared() < 0.0001D) {
return false;
}
horizontalDirection = horizontalDirection.normalize();
Vec3d targetFacing = target.getRotationVec(1.0F);
double dot = targetFacing.x * horizontalDirection.x + targetFacing.z * horizontalDirection.z;
return dot <= REAR_CONE_DOT;
}
}