Allow mobs to be hit

This commit is contained in:
2026-09-30 10:29:13 -03:00
parent 9e580f175e
commit 65f27d6099
8 changed files with 143 additions and 1 deletions
+30
View File
@@ -72,12 +72,15 @@ import {
type SavedItemEntity,
} from "./entity/item_entity.ts";
import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts";
import { create_entity, entity_type_ids } from "./entity/entity_types.ts";
import type { SavedEntity } from "./entity/entity.ts";
// how far from a player's eyes a block can be changed, a bit more than the client's reach
const MAX_REACH = 8;
// how hard a player hits with their fist, whatever they're holding. half a heart, like minecraft
const PLAYER_ATTACK_DAMAGE = 1;
// how far past a player's box items get picked up from, sideways and up or down, like minecraft
const PICKUP_REACH_XZ = 1;
const PICKUP_REACH_Y = 0.5;
@@ -733,6 +736,11 @@ export class GameServer {
this.#hit_block(player, message.x, message.y, message.z);
}
break;
case "attack_entity":
if (typeof message.id === "string") {
this.#attack_entity(player, message.id);
}
break;
case "use_item":
this.#use_item(player);
break;
@@ -805,6 +813,18 @@ export class GameServer {
}
}
// left click on an entity: hurts it and pushes it away. it can't be hurt again for a moment, see LivingEntity.hurt
#attack_entity(player: ServerPlayer, id: string) {
const entity = this.entities.get_entity(id);
if (!(entity instanceof LivingEntity) || !entity.alive || !this.#entity_in_reach(player, entity)) {
return;
}
const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const;
if (entity.hurt(PLAYER_ATTACK_DAMAGE, source)) {
player.vitals.add_exhaustion(EXHAUSTION.attack);
}
}
// right click at nothing: eating, or the item's on_use
#use_item(player: ServerPlayer): boolean {
return this.#eat(player) || this.#use_item_components(player);
@@ -1585,6 +1605,16 @@ export class GameServer {
return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH;
}
// from the eyes to the closest point of its box
#entity_in_reach(player: ServerPlayer, entity: LivingEntity) {
const eye_y = player.y + PLAYER_EYE_HEIGHT;
const half = entity.width / 2;
const dx = Math.max(entity.x - half - player.x, 0, player.x - entity.x - half);
const dy = Math.max(entity.y - eye_y, 0, eye_y - entity.y - entity.height);
const dz = Math.max(entity.z - half - player.z, 0, player.z - entity.z - half);
return dx * dx + dy * dy + dz * dz <= MAX_REACH * MAX_REACH;
}
#near_any_player(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
+1
View File
@@ -24,6 +24,7 @@ export const EXHAUSTION = {
jump: 0.05,
sprint_jump: 0.2,
break_block: 0.005,
attack: 0.1,
damage: 0.1,
heal_per_health: 6,
};