Improve multiplayer
This commit is contained in:
parent
220b20476f
commit
37954e2ef1
29 changed files with 321 additions and 267 deletions
5
backend/src/helper/get-time-in-milliseconds.ts
Normal file
5
backend/src/helper/get-time-in-milliseconds.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export const getTimeInMilliseconds = (): number => {
|
||||
const [seconds, nanoSeconds] = process.hrtime();
|
||||
|
||||
return seconds * 1000 + nanoSeconds / 1000 / 1000;
|
||||
};
|
||||
|
|
@ -83,14 +83,36 @@ server.listen(port, () => {
|
|||
console.log(`server started at http://localhost:${port}`);
|
||||
});
|
||||
|
||||
let deltas: Array<number> = [];
|
||||
|
||||
const handlePhysics = () => {
|
||||
const delta = deltaTimeCalculator.getNextDeltaTimeInMilliseconds();
|
||||
deltas.push(delta);
|
||||
const step = new StepCommand(delta);
|
||||
if (deltas.length > 100) {
|
||||
deltas.sort((a, b) => a - b);
|
||||
console.log(`Median physics time: ${deltas[50].toFixed(2)} ms`);
|
||||
console.log(
|
||||
`Memory used: ${(process.memoryUsage().rss / 1024 / 1024).toFixed(2)} MB`,
|
||||
);
|
||||
deltas = [];
|
||||
console.log(players.map((p) => p.latency));
|
||||
}
|
||||
|
||||
if (deltas.length > 100) {
|
||||
deltas.sort((a, b) => a - b);
|
||||
console.log(`Median physics time: ${deltas[50].toFixed(2)} ms`);
|
||||
console.log(
|
||||
`Memory used: ${(process.memoryUsage().rss / 1024 / 1024).toFixed(2)} MB`,
|
||||
);
|
||||
deltas = [];
|
||||
}
|
||||
|
||||
objects.sendCommand(step);
|
||||
players.forEach((p) => p.sendCommand(step));
|
||||
|
||||
const physicsDelta = deltaTimeCalculator.getDeltaTimeInMilliseconds();
|
||||
deltas.push(physicsDelta);
|
||||
const sleepTime = settings.targetPhysicsDeltaTimeInMilliseconds - physicsDelta;
|
||||
if (sleepTime >= settings.minPhysicsSleepTime) {
|
||||
setTimeout(handlePhysics, sleepTime);
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ export const createDungeon = (objects: PhysicalContainer) => {
|
|||
|
||||
let tunnelsCountSinceLastLight = 0;
|
||||
|
||||
for (let i = 0; i < 500000; i += 500) {
|
||||
const deltaHeight = (Random.getRandom() - 0.5) * 2000;
|
||||
for (let i = 0; i < 50000; i += 500) {
|
||||
const deltaHeight = (Random.getRandom() - 0.5) * 500;
|
||||
const height = previousEnd.y + deltaHeight;
|
||||
const currentEnd = vec2.fromValues(i, height);
|
||||
const currentToRadius = Random.getRandom() * 300 + 150;
|
||||
|
|
|
|||
|
|
@ -8,11 +8,14 @@ import {
|
|||
MoveActionCommand,
|
||||
serializesTo,
|
||||
clamp,
|
||||
last,
|
||||
Circle,
|
||||
} from 'shared';
|
||||
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
|
||||
import { CirclePhysical } from './circle-physical';
|
||||
import { Physical } from '../physics/physical';
|
||||
import { PhysicalContainer } from '../physics/containers/physical-container';
|
||||
import { Spring } from './spring';
|
||||
|
||||
@serializesTo(CharacterBase)
|
||||
export class CharacterPhysical extends CharacterBase implements Physical {
|
||||
|
|
@ -27,6 +30,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
|
|||
public rightFoot: CirclePhysical;
|
||||
|
||||
private movementActions: Array<MoveActionCommand> = [];
|
||||
private lastMovementAction: MoveActionCommand = new MoveActionCommand(vec2.create());
|
||||
|
||||
protected commandExecutors: CommandExecutors = {
|
||||
[StepCommand.type]: this.step.bind(this),
|
||||
|
|
@ -34,11 +38,11 @@ export class CharacterPhysical extends CharacterBase implements Physical {
|
|||
};
|
||||
|
||||
private static readonly headOffset = vec2.fromValues(0, 40);
|
||||
private static readonly leftFootOffset = vec2.fromValues(-20, -10);
|
||||
private static readonly rightFootOffset = vec2.fromValues(20, -10);
|
||||
private static readonly leftFootOffset = vec2.fromValues(-20, -35);
|
||||
private static readonly rightFootOffset = vec2.fromValues(20, -35);
|
||||
|
||||
constructor(private readonly container: PhysicalContainer) {
|
||||
super(id(), undefined, undefined, undefined);
|
||||
super(id());
|
||||
this.head = new CirclePhysical(
|
||||
vec2.clone(CharacterPhysical.headOffset),
|
||||
50,
|
||||
|
|
@ -76,6 +80,10 @@ export class CharacterPhysical extends CharacterBase implements Physical {
|
|||
return this;
|
||||
}
|
||||
|
||||
public get center(): vec2 {
|
||||
return this.head.center;
|
||||
}
|
||||
|
||||
public distance(target: vec2): number {
|
||||
return (
|
||||
Math.min(
|
||||
|
|
@ -87,92 +95,82 @@ export class CharacterPhysical extends CharacterBase implements Physical {
|
|||
}
|
||||
|
||||
private sumAndResetMovementActions(): vec2 {
|
||||
let direction: vec2;
|
||||
if (this.movementActions.length === 0) {
|
||||
return vec2.create();
|
||||
direction = vec2.clone(this.lastMovementAction.direction);
|
||||
} else {
|
||||
direction = this.movementActions.reduce(
|
||||
(sum, current) => vec2.add(sum, sum, current.direction),
|
||||
vec2.create(),
|
||||
);
|
||||
|
||||
vec2.scale(direction, direction, 1 / this.movementActions.length);
|
||||
|
||||
this.lastMovementAction = last(this.movementActions)!;
|
||||
this.movementActions = [];
|
||||
}
|
||||
|
||||
const movementForce = this.movementActions.reduce(
|
||||
(sum, current) => vec2.add(sum, sum, current.delta),
|
||||
vec2.create(),
|
||||
);
|
||||
|
||||
vec2.scale(movementForce, movementForce, 1 / this.movementActions.length);
|
||||
|
||||
this.movementActions = [];
|
||||
|
||||
return movementForce;
|
||||
return direction;
|
||||
}
|
||||
|
||||
public step(c: StepCommand) {
|
||||
const deltaTime = c.deltaTimeInMiliseconds;
|
||||
|
||||
this.head.applyForce(settings.gravitationalForce, deltaTime);
|
||||
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
|
||||
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
|
||||
|
||||
const movementForce = this.sumAndResetMovementActions();
|
||||
const deltaTime = c.deltaTimeInMiliseconds / 1000;
|
||||
|
||||
const direction = this.sumAndResetMovementActions();
|
||||
const isAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne;
|
||||
if (isAirborne) {
|
||||
this.jumpEnergyLeft -= deltaTime;
|
||||
} else {
|
||||
this.jumpEnergyLeft = settings.defaultJumpEnergy;
|
||||
}
|
||||
const xMax = deltaTime * settings.maxAccelerationX;
|
||||
const yMax = this.jumpEnergyLeft > 0 ? deltaTime * settings.maxAccelerationY : 0;
|
||||
this.jumpEnergyLeft += isAirborne ? -deltaTime : deltaTime;
|
||||
this.jumpEnergyLeft = clamp(this.jumpEnergyLeft, 0, settings.defaultJumpEnergy);
|
||||
|
||||
vec2.set(
|
||||
movementForce,
|
||||
clamp(movementForce.x, -xMax, xMax),
|
||||
clamp(movementForce.y, -yMax, yMax),
|
||||
const xMax = deltaTime * settings.maxAccelerationX;
|
||||
const yMax = this.jumpEnergyLeft > 0 ? settings.maxAccelerationY : 0;
|
||||
const movementForce = vec2.multiply(
|
||||
direction,
|
||||
direction,
|
||||
vec2.fromValues(xMax, yMax),
|
||||
);
|
||||
|
||||
const sumBody = vec2.add(vec2.create(), this.head.center, this.leftFoot.center);
|
||||
vec2.add(sumBody, sumBody, this.rightFoot.center);
|
||||
vec2.scale(sumBody, sumBody, 1 / 3);
|
||||
|
||||
const headPosition = vec2.add(vec2.create(), sumBody, CharacterPhysical.headOffset);
|
||||
|
||||
Spring.step(new Circle(headPosition, 0), this.head, 0, 30, deltaTime);
|
||||
|
||||
const footDistance = vec2.distance(
|
||||
CharacterPhysical.headOffset,
|
||||
CharacterPhysical.leftFootOffset,
|
||||
);
|
||||
|
||||
Spring.step(
|
||||
new Circle(this.head.center, this.head.radius),
|
||||
this.leftFoot,
|
||||
footDistance,
|
||||
25,
|
||||
deltaTime,
|
||||
);
|
||||
Spring.step(
|
||||
new Circle(this.head.center, this.head.radius),
|
||||
this.rightFoot,
|
||||
footDistance,
|
||||
25,
|
||||
deltaTime,
|
||||
);
|
||||
Spring.step(
|
||||
this.leftFoot,
|
||||
this.rightFoot,
|
||||
vec2.distance(CharacterPhysical.leftFootOffset, CharacterPhysical.rightFootOffset),
|
||||
100,
|
||||
deltaTime,
|
||||
);
|
||||
|
||||
this.head.applyForce(movementForce, deltaTime);
|
||||
this.leftFoot.applyForce(movementForce, deltaTime);
|
||||
this.rightFoot.applyForce(movementForce, deltaTime);
|
||||
|
||||
const bodyCenter = vec2.subtract(
|
||||
vec2.create(),
|
||||
this.head.center,
|
||||
CharacterPhysical.headOffset,
|
||||
);
|
||||
|
||||
const leftFootPositon = vec2.add(
|
||||
vec2.create(),
|
||||
bodyCenter,
|
||||
CharacterPhysical.leftFootOffset,
|
||||
);
|
||||
const rightFootPositon = vec2.add(
|
||||
vec2.create(),
|
||||
bodyCenter,
|
||||
CharacterPhysical.rightFootOffset,
|
||||
);
|
||||
|
||||
const leftFootDelta = vec2.subtract(
|
||||
vec2.create(),
|
||||
this.leftFoot.center,
|
||||
leftFootPositon,
|
||||
);
|
||||
|
||||
const rightFootDelta = vec2.subtract(
|
||||
vec2.create(),
|
||||
this.rightFoot.center,
|
||||
rightFootPositon,
|
||||
);
|
||||
|
||||
if (vec2.squaredLength(leftFootDelta) > 0) {
|
||||
vec2.scale(leftFootDelta, leftFootDelta, 0.001);
|
||||
this.head.applyForce(leftFootDelta, deltaTime);
|
||||
vec2.scale(leftFootDelta, leftFootDelta, -4);
|
||||
this.leftFoot.applyForce(leftFootDelta, deltaTime);
|
||||
}
|
||||
|
||||
if (vec2.squaredLength(rightFootDelta) > 0) {
|
||||
vec2.scale(rightFootDelta, rightFootDelta, 0.001);
|
||||
this.head.applyForce(rightFootDelta, deltaTime);
|
||||
vec2.scale(rightFootDelta, rightFootDelta, -4);
|
||||
this.rightFoot.applyForce(rightFootDelta, deltaTime);
|
||||
}
|
||||
this.head.applyForce(settings.gravitationalForce, deltaTime);
|
||||
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
|
||||
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
|
||||
|
||||
this.head.step(deltaTime);
|
||||
this.leftFoot.step(deltaTime);
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ export class CirclePhysical implements Circle, Physical {
|
|||
return vec2.distance(target, this.center) - this.radius;
|
||||
}
|
||||
|
||||
public distanceBetween(target: CirclePhysical): number {
|
||||
public distanceBetween(target: Circle): number {
|
||||
return vec2.distance(target.center, this.center) - this.radius - target.radius;
|
||||
}
|
||||
|
||||
|
|
@ -94,17 +94,17 @@ export class CirclePhysical implements Circle, Physical {
|
|||
this._boundingBox.yMax = this.center.y + this._radius;
|
||||
}
|
||||
|
||||
public applyForce(force: vec2, timeInMilliseconds: number) {
|
||||
public applyForce(force: vec2, timeInSeconds: number) {
|
||||
vec2.add(
|
||||
this.velocity,
|
||||
this.velocity,
|
||||
vec2.scale(vec2.create(), force, timeInMilliseconds),
|
||||
vec2.scale(vec2.create(), force, timeInSeconds),
|
||||
);
|
||||
|
||||
vec2.set(
|
||||
this.velocity,
|
||||
clamp(this.velocity.x, -settings.maxVelocityX, settings.maxVelocityX),
|
||||
this.velocity.y,
|
||||
clamp(this.velocity.y, -settings.maxVelocityY, settings.maxVelocityY),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -112,14 +112,15 @@ export class CirclePhysical implements Circle, Physical {
|
|||
this.velocity = vec2.create();
|
||||
}
|
||||
|
||||
public step(timeInMilliseconds: number): boolean {
|
||||
public step(deltaTimeInSeconds: number): boolean {
|
||||
vec2.scale(
|
||||
this.velocity,
|
||||
this.velocity,
|
||||
Math.pow(settings.velocityAttenuation, timeInMilliseconds),
|
||||
Math.pow(settings.velocityAttenuation, deltaTimeInSeconds),
|
||||
);
|
||||
|
||||
const distance = vec2.scale(vec2.create(), this.velocity, timeInMilliseconds);
|
||||
const distance = vec2.scale(vec2.create(), this.velocity, deltaTimeInSeconds);
|
||||
|
||||
const distanceLength = vec2.length(distance);
|
||||
const stepCount = Math.ceil(distanceLength / settings.physicsMaxStep);
|
||||
vec2.scale(distance, distance, 1 / stepCount);
|
||||
|
|
@ -127,13 +128,20 @@ export class CirclePhysical implements Circle, Physical {
|
|||
let wasHit = false;
|
||||
|
||||
for (let i = 0; i < stepCount; i++) {
|
||||
const { normal, tangent, hitSurface } = moveCircle(
|
||||
const { tangent, hitSurface } = moveCircle(
|
||||
this,
|
||||
distance,
|
||||
vec2.clone(distance),
|
||||
this.container.findIntersecting(this.boundingBox),
|
||||
);
|
||||
|
||||
if (hitSurface) {
|
||||
vec2.scale(this.velocity, tangent!, vec2.dot(tangent!, this.velocity));
|
||||
if (
|
||||
vec2.length(this.velocity) <
|
||||
settings.frictionMinVelocity * deltaTimeInSeconds
|
||||
) {
|
||||
this.velocity = vec2.create();
|
||||
}
|
||||
wasHit = true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
37
backend/src/objects/spring.ts
Normal file
37
backend/src/objects/spring.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { vec2 } from 'gl-matrix';
|
||||
import { Circle } from 'shared';
|
||||
import { CirclePhysical } from './circle-physical';
|
||||
|
||||
export class Spring {
|
||||
constructor(
|
||||
private a: CirclePhysical | Circle,
|
||||
private b: CirclePhysical | Circle,
|
||||
private distance: number,
|
||||
private strength: number,
|
||||
) {}
|
||||
|
||||
public step(deltaTimeInSeconds: number) {
|
||||
Spring.step(this.a, this.b, this.distance, this.strength, deltaTimeInSeconds);
|
||||
}
|
||||
|
||||
public static step(
|
||||
a: CirclePhysical | Circle,
|
||||
b: CirclePhysical | Circle,
|
||||
distance: number,
|
||||
strength: number,
|
||||
deltaTimeInSeconds: number,
|
||||
) {
|
||||
const length = vec2.dist(a.center, b.center) - distance;
|
||||
|
||||
const abDirection = vec2.subtract(vec2.create(), b.center, a.center);
|
||||
vec2.normalize(abDirection, abDirection);
|
||||
const force = vec2.scale(abDirection, abDirection, strength * length);
|
||||
if (a instanceof CirclePhysical) {
|
||||
a.applyForce(force, deltaTimeInSeconds);
|
||||
}
|
||||
if (b instanceof CirclePhysical) {
|
||||
vec2.scale(force, force, -1);
|
||||
b.applyForce(force, deltaTimeInSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -73,10 +73,11 @@ export const moveCircle = (
|
|||
|
||||
circle.center = vec2.add(circle.center, circle.center, approxNormal);
|
||||
|
||||
vec2.normalize(approxNormal, approxNormal);
|
||||
return {
|
||||
realDelta: delta,
|
||||
hitSurface: true,
|
||||
normal: vec2.normalize(approxNormal, approxNormal),
|
||||
normal: approxNormal,
|
||||
tangent: rotate90Deg(approxNormal),
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,11 +6,13 @@ import {
|
|||
DeleteObjectsCommand,
|
||||
MoveActionCommand,
|
||||
serialize,
|
||||
SetViewAreaActionCommand,
|
||||
TransportEvents,
|
||||
UpdateObjectsCommand,
|
||||
StepCommand,
|
||||
SetAspectRatioActionCommand,
|
||||
calculateViewArea,
|
||||
} from 'shared';
|
||||
import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds';
|
||||
import { CharacterPhysical } from '../objects/character-physical';
|
||||
|
||||
import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
|
||||
|
|
@ -19,16 +21,31 @@ import { Physical } from '../physics/physical';
|
|||
|
||||
export class Player extends CommandReceiver {
|
||||
private character: CharacterPhysical;
|
||||
private aspectRatio: number = 16 / 9;
|
||||
private isActive = true;
|
||||
|
||||
private objectsPreviouslyInViewArea: Array<Physical> = [];
|
||||
private objectsInViewArea: Array<Physical> = [];
|
||||
|
||||
private pingTime?: number;
|
||||
private _latency?: number;
|
||||
public measureLatency() {
|
||||
this.pingTime = getTimeInMilliseconds();
|
||||
this.socket.emit(TransportEvents.Ping);
|
||||
if (this.isActive) {
|
||||
setTimeout(this.measureLatency.bind(this), 10000);
|
||||
}
|
||||
}
|
||||
|
||||
public get latency(): number | undefined {
|
||||
return this._latency;
|
||||
}
|
||||
|
||||
protected commandExecutors: CommandExecutors = {
|
||||
[StepCommand.type]: this.sendObjects.bind(this),
|
||||
[SetViewAreaActionCommand.type]: this.setViewArea.bind(this),
|
||||
[MoveActionCommand.type]: (c: MoveActionCommand) => {
|
||||
this.character.sendCommand(c);
|
||||
},
|
||||
[SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) =>
|
||||
(this.aspectRatio = v.aspectRatio),
|
||||
[MoveActionCommand.type]: (c: MoveActionCommand) => this.character.sendCommand(c),
|
||||
};
|
||||
|
||||
constructor(
|
||||
|
|
@ -47,18 +64,24 @@ export class Player extends CommandReceiver {
|
|||
serialize(new CreatePlayerCommand(this.character)),
|
||||
);
|
||||
|
||||
socket.on(
|
||||
TransportEvents.Pong,
|
||||
() => (this._latency = getTimeInMilliseconds() - this.pingTime!),
|
||||
);
|
||||
|
||||
this.measureLatency();
|
||||
|
||||
this.sendObjects();
|
||||
}
|
||||
|
||||
public setViewArea(c: SetViewAreaActionCommand) {
|
||||
const viewArea = new BoundingBox();
|
||||
viewArea.topLeft = c.viewArea.topLeft;
|
||||
viewArea.size = c.viewArea.size;
|
||||
|
||||
this.objectsInViewArea = this.objects.findIntersecting(viewArea);
|
||||
}
|
||||
|
||||
public sendObjects() {
|
||||
const viewArea = calculateViewArea(this.character.center, this.aspectRatio, 1.5);
|
||||
const bb = new BoundingBox();
|
||||
bb.topLeft = viewArea.topLeft;
|
||||
bb.size = viewArea.size;
|
||||
|
||||
this.objectsInViewArea = this.objects.findIntersecting(bb);
|
||||
|
||||
const newlyIntersecting = this.objectsInViewArea.filter(
|
||||
(o) => !this.objectsPreviouslyInViewArea.includes(o),
|
||||
);
|
||||
|
|
@ -103,6 +126,7 @@ export class Player extends CommandReceiver {
|
|||
}
|
||||
|
||||
public destroy() {
|
||||
this.isActive = false;
|
||||
this.character.destroy();
|
||||
this.objects.removeObject(this.character);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue