Files
bworld/mods/dangerous_business/scripts/shared.ts
T
2026-11-15 21:55:17 -03:00

38 lines
1.7 KiB
TypeScript

import type { SharedContext } from "cubi/shared";
export const DOOR = "dangerous_business:door";
const FACINGS = ["north", "east", "south", "west"];
// the way along the ground each facing goes, in FACINGS' order
const FACING_STEPS = [[0, -1], [1, 0], [0, 1], [-1, 0]];
export function shared(ctx: SharedContext) {
register_door(ctx);
}
// a door is two blocks, its lower half (half 0) and its upper half (half 1), with the same states. it faces the way the
// player placing it looks, and is hinged on the side away from a door of the same kind beside it, so the two meet in
// the middle as a double door. without one, on the side of the block the player clicked toward. the server places the
// upper half and takes away the other half when one breaks, see register_door in main.ts
function register_door(ctx: SharedContext) {
ctx.components.register_block(DOOR, {
state_for_placement(placement): Record<string, number> {
const facing = FACINGS.indexOf(placement.facing);
const { x, y, z } = placement;
const door_at = ([step_x, step_z]: number[]) => {
const id = ctx.world.get_block(x + step_x, y, z + step_z);
return id !== undefined && DOOR in ctx.blocks.components(id) &&
ctx.world.get_state(x + step_x, y, z + step_z, "half") === 0;
};
const door_left = door_at(FACING_STEPS[(facing + 3) % 4]);
const door_right = door_at(FACING_STEPS[(facing + 1) % 4]);
if (door_left !== door_right) return { facing, half: 0, hinge: door_left ? 1 : 0 };
const [step_x, step_z] = FACING_STEPS[facing];
const [hit_x, , hit_z] = placement.hit;
const right = (step_x < 0 && hit_z < 0.5) || (step_x > 0 && hit_z > 0.5) ||
(step_z < 0 && hit_x > 0.5) || (step_z > 0 && hit_x < 0.5);
return { facing, half: 0, hinge: right ? 1 : 0 };
},
});
}