Improve moviment !

This commit is contained in:
2026-09-27 15:37:09 -03:00
parent 5298ff7cf3
commit 9f47c709f1
10 changed files with 285 additions and 37 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ export class Camera {
setup(entity: Entity, partial_tick: number) {
const { x, y, z } = entity.render_position(partial_tick);
this.x = x;
this.y = y + entity.eye_height;
this.y = y + entity.render_eye_height(partial_tick);
this.z = z;
this.yaw = entity.yaw;
this.pitch = entity.pitch;
+15 -1
View File
@@ -30,6 +30,12 @@ export abstract class Entity {
// what's left of its speed after each tick in the air, like minecraft's 0.98. it caps falling speed
// at 49 * -gravity * TICK_DELTA, 78 blocks per second with minecraft's gravity
drag = 0.98;
// what it walks up onto without jumping, see move_body
step_height = 0;
// it can still step up this many ticks after leaving the ground
step_grace_ticks = 0;
// ticks since it was last on the ground
#air_ticks = 0;
// which way it hit something on each axis in the last move: 1 or -1, 0 for nothing.
// 1 on y means it's standing on something
@@ -71,15 +77,23 @@ export abstract class Entity {
};
}
// how high the eyes are, for the camera. a frame is partial_tick of the way to the next tick
render_eye_height(_partial_tick: number) {
return this.eye_height;
}
// one step of the game, TICK_DELTA seconds
abstract tick(): void;
// falls and moves by its velocity for one tick (see move_body), then slows down from drag
move() {
const collisions = move_body(this, this.gravity, (x, y, z) => this.level.has_collision(x, y, z));
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
const can_step = this.#air_ticks <= this.step_grace_ticks && this.vy <= 0;
const collisions = move_body(this, this.gravity, is_solid, this.step_height, can_step);
this.colliding_x = collisions.x;
this.colliding_y = collisions.y;
this.colliding_z = collisions.z;
this.#air_ticks = this.on_ground ? 0 : this.#air_ticks + 1;
this.vx *= this.drag;
this.vy *= this.drag;
this.vz *= this.drag;
+61 -24
View File
@@ -1,3 +1,5 @@
import { PLAYER_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts";
import { back_off_from_edge } from "$/common/physics.ts";
import type { Client } from "../client.ts";
import { InputManager } from "../input_manager.ts";
import { ClientInventories } from "../inventory.ts";
@@ -9,6 +11,24 @@ const SEND_POSITION_TICKS = 2;
// ticks after a jump before holding jump can jump again, like minecraft's noJumpDelay. a jump is longer than this in
// the air, so holding it jumps again as soon as it lands
const JUMP_DELAY_TICKS = 10;
// like minecraft: sneaking is 30% of walking speed and lowers the eyes 0.35, which ease there by half each tick
const SNEAK_SPEED = 0.3;
const SNEAK_EYE_HEIGHT = PLAYER_EYE_HEIGHT - 0.35;
const EYE_EASE = 0.5;
// sneaking keeps it from walking off anything taller than this
const SNEAK_MAX_DROP = 0.6;
// what the keys ask for this tick. x is right, z is back, as -1 to 1
interface MoveInput {
x: number;
z: number;
jump: boolean;
sprint: boolean;
sneak: boolean;
}
// while a screen is open, like minecraft ignoring movement keys then
const NO_INPUT: MoveInput = { x: 0, z: 0, jump: false, sprint: false, sneak: false };
// the player this client controls, like minecraft's LocalPlayer
export class LocalPlayer extends Player {
@@ -26,6 +46,8 @@ export class LocalPlayer extends Player {
#ticks_since_sent = 0;
// counts down every tick, letting go of jump clears it
#jump_delay = 0;
sneaking = false;
#prev_eye_height = PLAYER_EYE_HEIGHT;
constructor(client: Client, id: string, name: string) {
super(client.level, id, name);
@@ -33,12 +55,25 @@ export class LocalPlayer extends Player {
}
tick() {
if (!this.client.screen) {
this.#apply_input();
} else {
this.#jump_delay = 0;
}
this.#apply_input(this.client.screen ? NO_INPUT : this.#read_input());
this.#prev_eye_height = this.eye_height;
const eye_height = this.sneaking ? SNEAK_EYE_HEIGHT : PLAYER_EYE_HEIGHT;
this.eye_height += (eye_height - this.eye_height) * EYE_EASE;
const was_on_ground = this.on_ground;
// not while jumping, so it can still jump off a ledge
if (this.sneaking && this.on_ground && this.vy <= 0) {
const is_solid = (x: number, y: number, z: number) => this.level.has_collision(x, y, z);
const [dx, dz] = back_off_from_edge(
this,
this.vx * TICK_DELTA,
this.vz * TICK_DELTA,
SNEAK_MAX_DROP,
is_solid,
);
this.vx = dx / TICK_DELTA;
this.vz = dz / TICK_DELTA;
}
this.move();
this.#send_position(this.on_ground && !was_on_ground);
}
@@ -52,40 +87,42 @@ export class LocalPlayer extends Player {
this.pitch = Math.max(-limit, Math.min(limit, this.pitch));
}
// walking relative to where it's looking
#apply_input() {
// the eyes between the last tick and this one, for the camera
override render_eye_height(partial_tick: number) {
return this.#prev_eye_height + (this.eye_height - this.#prev_eye_height) * partial_tick;
}
#read_input(): MoveInput {
const options = this.client.options;
let input_x = 0;
let input_z = 0;
if (InputManager.is_key_down(options.key_left)) {
input_x -= 1;
}
if (InputManager.is_key_down(options.key_right)) {
input_x += 1;
}
if (InputManager.is_key_down(options.key_forward)) {
input_z -= 1;
}
if (InputManager.is_key_down(options.key_back)) {
input_z += 1;
}
const down = (key: typeof options.key_jump) => InputManager.is_key_down(key);
return {
x: Number(down(options.key_right)) - Number(down(options.key_left)),
z: Number(down(options.key_back)) - Number(down(options.key_forward)),
jump: down(options.key_jump),
sprint: down(options.key_sprint),
sneak: down(options.key_sneak),
};
}
// walking relative to where it's looking
#apply_input(input: MoveInput) {
let { x: input_x, z: input_z } = input;
const size = Math.hypot(input_x, input_z);
if (size > 0) {
input_x /= size;
input_z /= size;
}
this.sneaking = input.sneak;
const sin = Math.sin(this.yaw);
const cos = Math.cos(this.yaw);
const speed = this.move_speed * (InputManager.is_key_down(options.key_sprint) ? 1.75 : 1);
const speed = this.move_speed * (input.sneak ? SNEAK_SPEED : input.sprint ? 1.75 : 1);
this.vx = (sin * input_z + cos * input_x) * speed;
this.vz = (cos * input_z - sin * input_x) * speed;
this.#jump_delay = Math.max(0, this.#jump_delay - 1);
if (!InputManager.is_key_down(options.key_jump)) {
if (!input.jump) {
this.#jump_delay = 0;
} else if (this.on_ground && this.#jump_delay === 0) {
this.vy += this.jump_force;
+5
View File
@@ -6,6 +6,11 @@ import { Entity } from "./entity.ts";
export abstract class Player extends Entity {
name: string;
// like minecraft's players: slabs yes, full blocks need a jump
override step_height = 0.6;
// more than minecraft, where it's only the tick it leaves the ground: stepping from the edge of a block onto one
// diagonal to it drops it a little first, this lets it still step up onto that one
override step_grace_ticks = 3;
// undefined draws the default skin
skin: Texture | undefined;
// 3 pixel wide arms, for skins made for them
+6
View File
@@ -122,6 +122,12 @@ export class InputManager {
}
});
// keys let go while the window isn't focused never send keyup, so they'd stay held
self.addEventListener("blur", () => {
this.keys_down.clear();
this.mouse_buttons_down.clear();
});
self.addEventListener("keyup", (e) => {
e.preventDefault();
e.stopPropagation();
+2
View File
@@ -10,6 +10,8 @@ export class Options {
key_right: KeyCode = "KeyD";
key_jump: KeyCode = "Space";
key_sprint: KeyCode = "ShiftLeft";
// not shift like minecraft, that's sprint. ctrl isn't either: ctrl+w closes the tab and a page can't stop it
key_sneak: KeyCode = "KeyC";
key_inventory: KeyCode = "KeyE";
// with ctrl it drops the whole stack
key_drop: KeyCode = "KeyQ";
+1 -1
View File
@@ -26,7 +26,7 @@ export const SEA_LEVEL = 64;
export const CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE;
// the player's collision box, position is the middle of its feet
export const PLAYER_WIDTH = 0.55;
export const PLAYER_WIDTH = 0.6;
export const PLAYER_HEIGHT = 1.79;
export const PLAYER_EYE_HEIGHT = 1.69;
+98 -10
View File
@@ -26,10 +26,20 @@ export interface Collisions {
z: number;
}
// falls and moves a body by its velocity for one tick. like minecraft it moves along y, then x, then z, each
// time only as far as it can before touching a block, and stops its velocity on the axes it hit something.
// blocks it's already inside don't stop it, so it can get out of them
export function move_body(body: Body, gravity: number, is_solid: (x: number, y: number, z: number) => boolean) {
// falls and moves a body by its velocity for one tick. like minecraft it moves along y first, then along whichever
// of x and z it's moving more on, so walking diagonally past a corner slides along it instead of snagging. each time
// only as far as it can before touching a block, and stops its velocity on the axes it hit something.
// blocks it's already inside don't stop it, so it can get out of them.
// with a step height, a body that was on the ground (or lands during this move) and walks into something at most
// that tall steps up onto it, like minecraft's Entity.collide. that also covers the tick it starts to fall: it has
// already dropped a little, so the next block's top is a small step up instead of a wall to slide down
export function move_body(
body: Body,
gravity: number,
is_solid: (x: number, y: number, z: number) => boolean,
step_height = 0,
on_ground = false,
) {
// the average of this tick's start and end speed, so the arc is the same at any tick rate
const wanted_y = (body.vy + gravity * TICK_DELTA / 2) * TICK_DELTA;
body.vy += gravity * TICK_DELTA;
@@ -38,12 +48,15 @@ export function move_body(body: Body, gravity: number, is_solid: (x: number, y:
const half = body.width / 2;
const min = [body.x - half, body.y, body.z - half];
const max = [body.x + half, body.y + body.height, body.z + half];
const moved = [0, 0, 0];
for (const axis of [1, 0, 2]) {
const distance = clip(min, max, axis, wanted[axis], is_solid);
min[axis] += distance;
max[axis] += distance;
moved[axis] = distance;
let moved = sweep([...min], [...max], wanted, [1, ...horizontal_order(wanted)], is_solid);
const blocked_sideways = moved[0] !== wanted[0] || moved[2] !== wanted[2];
const landed = moved[1] !== wanted[1] && wanted[1] < 0;
if (step_height > 0 && blocked_sideways && (on_ground || landed)) {
const stepped = step_up([...min], [...max], wanted, step_height, is_solid);
if (stepped[0] ** 2 + stepped[2] ** 2 > moved[0] ** 2 + moved[2] ** 2) {
moved = stepped;
}
}
const hit = (axis: number) => moved[axis] !== wanted[axis] ? -Math.sign(wanted[axis]) : 0;
@@ -58,6 +71,44 @@ export function move_body(body: Body, gravity: number, is_solid: (x: number, y:
return collisions;
}
// x then z, or z then x when it's moving more along z
function horizontal_order(wanted: number[]) {
return Math.abs(wanted[0]) < Math.abs(wanted[2]) ? [2, 0] : [0, 2];
}
// moves the box along each axis in turn, as far as it can. returns how far it went on each
function sweep(
min: number[],
max: number[],
wanted: number[],
axes: number[],
is_solid: (x: number, y: number, z: number) => boolean,
) {
const moved = [0, 0, 0];
for (const axis of axes) {
const distance = clip(min, max, axis, wanted[axis], is_solid);
min[axis] += distance;
max[axis] += distance;
moved[axis] = distance;
}
return moved;
}
// up by the step height (or to the ceiling), across, then back down onto whatever it's standing on, as far as it
// would have gone down anyway
function step_up(
min: number[],
max: number[],
wanted: number[],
step_height: number,
is_solid: (x: number, y: number, z: number) => boolean,
) {
const up = sweep(min, max, [0, step_height, 0], [1], is_solid)[1];
const across = sweep(min, max, wanted, horizontal_order(wanted), is_solid);
const down = sweep(min, max, [0, wanted[1] - up, 0], [1], is_solid)[1];
return [across[0], up + down, across[2]];
}
// how far the box can go along an axis before it runs into a block
function clip(
min: number[],
@@ -94,3 +145,40 @@ function clip(
}
return distance;
}
// how far a sneaking body on the ground can move this tick without walking off an edge, like minecraft's
// Player.maybeBackOffFromEdge: each axis is cut back until there's something within `drop` below the moved box
export function back_off_from_edge(
body: Body,
dx: number,
dz: number,
drop: number,
is_solid: (x: number, y: number, z: number) => boolean,
): [number, number] {
const step = 0.05;
const toward_zero = (d: number) => Math.abs(d) <= step ? 0 : d - Math.sign(d) * step;
const falls = (mx: number, mz: number) => {
const half = body.width / 2;
const min = [body.x - half + mx, body.y - drop, body.z - half + mz];
const max = [body.x + half + mx, body.y, body.z + half + mz];
return !overlaps_solid(min, max, is_solid);
};
while (dx !== 0 && falls(dx, 0)) dx = toward_zero(dx);
while (dz !== 0 && falls(0, dz)) dz = toward_zero(dz);
while (dx !== 0 && dz !== 0 && falls(dx, dz)) {
dx = toward_zero(dx);
dz = toward_zero(dz);
}
return [dx, dz];
}
function overlaps_solid(min: number[], max: number[], is_solid: (x: number, y: number, z: number) => boolean) {
for (let x = Math.floor(min[0] + EPSILON); x <= Math.floor(max[0] - EPSILON); x++) {
for (let y = Math.floor(min[1] + EPSILON); y <= Math.floor(max[1] - EPSILON); y++) {
for (let z = Math.floor(min[2] + EPSILON); z <= Math.floor(max[2] - EPSILON); z++) {
if (is_solid(x, y, z)) return true;
}
}
}
return false;
}
+53
View File
@@ -91,3 +91,56 @@ Deno.test("the position is sent on the tick it lands, so the server sees it touc
InputManager.keys_down.clear();
assert(landings >= 5, `landed ${landings} times`);
});
Deno.test("opening a screen while walking stops the player", () => {
const { player } = setup();
const client = player.client as unknown as { screen: unknown };
InputManager.keys_down.add("KeyW");
for (let tick = 0; tick < 5; tick++) player.tick();
client.screen = {};
player.tick();
const z = player.z;
for (let tick = 0; tick < 20; tick++) player.tick();
InputManager.keys_down.clear();
assertEquals(player.z, z);
assertEquals([player.vx, player.vz], [0, 0]);
});
Deno.test("sneaking doesn't walk off edges, from any direction, but still jumps off them", () => {
for (const [key, yaw] of [["KeyW", 0], ["KeyW", Math.PI / 4], ["KeyD", 0], ["KeyS", 1], ["KeyA", 2.5]] as const) {
// a 3x3 platform with nothing around it
const { player } = setup();
const level = player.level as unknown as { has_collision: (x: number, y: number, z: number) => boolean };
level.has_collision = (x, y, z) => y === -1 && x >= 0 && x < 3 && z >= 0 && z < 3;
player.set_position(1.5, 0, 1.5);
player.yaw = yaw;
run(player, 1, () => false);
InputManager.keys_down.add("KeyC");
InputManager.keys_down.add(key);
for (let tick = 0; tick < 60; tick++) player.tick();
assertEquals(player.y, 0, `fell off with ${key} at yaw ${yaw}`);
assert(player.on_ground);
InputManager.keys_down.add("Space");
for (let tick = 0; tick < 60; tick++) player.tick();
InputManager.keys_down.clear();
assert(player.y < -1, "jumped off");
}
});
Deno.test("stepping from the edge of a block onto the one diagonal to it doesn't fall between them", () => {
// floor only at (0, 0) and (1, 1)
const { player } = setup();
const level = player.level as unknown as { has_collision: (x: number, y: number, z: number) => boolean };
level.has_collision = (x, y, z) => y === -1 && ((x === 0 && z === 0) || (x === 1 && z === 1));
// on the +x edge of the first block, hanging over it, then walking diagonally to the other
player.set_position(1, 0, 0.3);
run(player, 1, () => false);
player.yaw = -3 * Math.PI / 4;
InputManager.keys_down.add("KeyW");
for (let tick = 0; tick < 20 && !(player.x > 1.3 && player.z > 1.3); tick++) player.tick();
InputManager.keys_down.clear();
assert(player.x > 1.3 && player.z > 1.3, "got over the second block");
assertEquals(player.y, 0);
assert(player.on_ground);
});
+43
View File
@@ -0,0 +1,43 @@
import { assert, assertAlmostEquals } from "@std/assert";
import { move_body } from "$/common/physics.ts";
const body = (x: number, z: number, vx: number, vz: number) => ({ x, y: 0, z, vx, vy: 0, vz, width: 0.6, height: 1.8 });
// a block at x 0 to 1, z 1 to 2, on a floor
const solid = (x: number, y: number, z: number) => y === -1 || (x === 0 && z === 1 && y === 0);
Deno.test("moving diagonally into a corner keeps going the way it's moving most, like minecraft", () => {
// mostly +z, from just beside the corner: z goes first, so the small x move is what the block stops
const mostly_z = body(-0.33, 0.65, 1, 4);
move_body(mostly_z, 0, solid);
assertAlmostEquals(mostly_z.z, 0.85);
assertAlmostEquals(mostly_z.x, -0.3);
// mostly +x: x goes first, and the small z move is stopped at the block's face
const mostly_x = body(-0.33, 0.65, 4, 1.2);
move_body(mostly_x, 0, solid);
assertAlmostEquals(mostly_x.x, -0.13);
assertAlmostEquals(mostly_x.z, 0.7);
});
Deno.test("a body on the ground steps up onto something low, not onto a full block, and only with a step height", () => {
// just walked off something, 0.1 below the top of the block at x 1 that it's walking into
const next_block = (x: number, y: number, z: number) => x === 1 && y === -1 && z === 0;
const dipped = () => ({ ...body(0.65, 0.5, 4, 0), y: -0.1 });
const stepping = dipped();
move_body(stepping, -32, next_block, 0.6, true);
assertAlmostEquals(stepping.y, 0, 1e-9);
assertAlmostEquals(stepping.x, 0.85);
// without a step height it's a wall, and it slides down it
const item = dipped();
move_body(item, -32, next_block, 0, true);
assertAlmostEquals(item.x, 0.7);
assert(item.y < -0.1);
// a full block is too tall to step onto
const wall = { ...body(0.5, 0.5, 4, 0), y: 0 };
move_body(wall, -32, (x, y, z) => y === -1 || (x === 1 && y === 0 && z === 0), 0.6, true);
assertAlmostEquals(wall.x, 0.7);
assertAlmostEquals(wall.y, 0);
});