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
+43 -1
View File
@@ -18,6 +18,13 @@ import { Connection } from "./network.ts";
import { PauseScreen } from "./gui/pause_screen.ts";
import { back_to_title } from "./gui/title_screen.ts";
import { TICK_DELTA } from "$/common/constants.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityJson } from "$/common/mod_data.ts";
// how far from the eyes entities can be hit, like minecraft
const ENTITY_REACH = 3;
// how far from the eyes blocks can be broken and used
const BLOCK_REACH = 6;
// after a long stall (a hidden tab, a debugger) the game skips ahead instead of running every missed tick at once
const MAX_TICKS_PER_FRAME = 10;
@@ -39,6 +46,8 @@ export class Client {
screens: GuiScreen[] = [];
// what the player is looking at, updated every frame
hit_result: BlockHitResult | undefined;
// the entity being looked at, closer than any block. hit_result is undefined then
entity_hit: RemoteEntity | undefined;
debugging = false;
// seconds of game time not ticked yet
@@ -169,7 +178,7 @@ export class Client {
}
InputManager.set_mouse_grabbed(!this.screen);
this.hit_result = this.level.pick(player.x, player.y + player.eye_height, player.z, player.yaw, player.pitch);
this.#pick();
this.#handle_block_interaction();
if (!this.screen && !closed_screen) {
@@ -235,6 +244,31 @@ export class Client {
}
}
// what's under the crosshair: an entity, or the first block in front of it
#pick() {
const player = this.player;
const eye_y = player.y + player.eye_height;
const picked = this.level.pick_entity(
player.x,
eye_y,
player.z,
player.yaw,
player.pitch,
ENTITY_REACH,
(entity) => entity instanceof RemoteEntity && !entity.dead && is_hittable(entity),
);
// a block in front of the entity hides it
this.hit_result = this.level.pick(
player.x,
eye_y,
player.z,
player.yaw,
player.pitch,
picked?.distance ?? BLOCK_REACH,
);
this.entity_hit = picked && !this.hit_result ? picked.entity as RemoteEntity : undefined;
}
// clicks happen right away, holding to break advances in tick()
#handle_block_interaction() {
const hit = this.hit_result;
@@ -253,6 +287,9 @@ export class Client {
this.game_renderer.hand.swing();
}
if (this.entity_hit && InputManager.is_mouse_pressed(0)) {
this.game_mode.attack(this.entity_hit);
}
if (hit) {
if (InputManager.is_mouse_pressed(0)) {
this.game_mode.start_destroy_block(hit);
@@ -286,3 +323,8 @@ export class Client {
}
}
}
// mobs can be hit, scripted entities like the fishing hook can't. kinds the client doesn't know are left to the server
function is_hittable(entity: RemoteEntity) {
return EverythingRegistry.get<EntityJson>("entities", entity.type)?.behavior !== "scripted";
}