Improve multiplayer

This commit is contained in:
schmelczerandras 2020-10-08 13:16:05 +02:00 committed by Schmelczer András
parent 220b20476f
commit 37954e2ef1
29 changed files with 321 additions and 267 deletions

View file

@ -12,7 +12,8 @@
"**/node_modules": true, "**/node_modules": true,
"**/package-lock.json": true, "**/package-lock.json": true,
"**/dist": true, "**/dist": true,
"**/lib": true "**/lib": true,
"**/.firebase": true
}, },
"editor.tabSize": 2, "editor.tabSize": 2,
"editor.detectIndentation": false, "editor.detectIndentation": false,
@ -42,10 +43,10 @@
"workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached", "workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached",
"workspaceFolder": "/workspace", "workspaceFolder": "/workspace",
"mounts": [ "mounts": [
"source=decla-red-root-node_modules-static,target=/workspace/node_modules,type=volume", "source=decla-red-root-node_modules-volume,target=/workspace/node_modules,type=volume",
"source=decla-red-frontend-node_modules-static,target=/workspace/frontend/node_modules,type=volume", "source=decla-red-frontend-node_modules-volume,target=/workspace/frontend/node_modules,type=volume",
"source=decla-red-backend-node_modules-static,target=/workspace/backend/node_modules,type=volume", "source=decla-red-backend-node_modules-volume,target=/workspace/backend/node_modules,type=volume",
"source=decla-red-shared-node_modules-static,target=/workspace/shared/node_modules,type=volume" "source=decla-red-shared-node_modules-volume,target=/workspace/shared/node_modules,type=volume"
], ],
"forwardPorts": [3000, 8080], "forwardPorts": [3000, 8080],
"postCreateCommand": "chown node:node ./**/node_modules && npm install && npm run initialize && npm run build" "postCreateCommand": "chown node:node ./**/node_modules && npm install && npm run initialize && npm run build"

2
.gitattributes vendored
View file

@ -1,2 +1,2 @@
*.psd filter=lfs diff=lfs merge=lfs -text *.psd filter=lfs diff=lfs merge=lfs -text
* text=auto * text=auto eol=lf

View file

@ -0,0 +1,5 @@
export const getTimeInMilliseconds = (): number => {
const [seconds, nanoSeconds] = process.hrtime();
return seconds * 1000 + nanoSeconds / 1000 / 1000;
};

View file

@ -83,14 +83,36 @@ server.listen(port, () => {
console.log(`server started at http://localhost:${port}`); console.log(`server started at http://localhost:${port}`);
}); });
let deltas: Array<number> = [];
const handlePhysics = () => { const handlePhysics = () => {
const delta = deltaTimeCalculator.getNextDeltaTimeInMilliseconds(); const delta = deltaTimeCalculator.getNextDeltaTimeInMilliseconds();
deltas.push(delta);
const step = new StepCommand(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); objects.sendCommand(step);
players.forEach((p) => p.sendCommand(step)); players.forEach((p) => p.sendCommand(step));
const physicsDelta = deltaTimeCalculator.getDeltaTimeInMilliseconds(); const physicsDelta = deltaTimeCalculator.getDeltaTimeInMilliseconds();
deltas.push(physicsDelta);
const sleepTime = settings.targetPhysicsDeltaTimeInMilliseconds - physicsDelta; const sleepTime = settings.targetPhysicsDeltaTimeInMilliseconds - physicsDelta;
if (sleepTime >= settings.minPhysicsSleepTime) { if (sleepTime >= settings.minPhysicsSleepTime) {
setTimeout(handlePhysics, sleepTime); setTimeout(handlePhysics, sleepTime);

View file

@ -10,8 +10,8 @@ export const createDungeon = (objects: PhysicalContainer) => {
let tunnelsCountSinceLastLight = 0; let tunnelsCountSinceLastLight = 0;
for (let i = 0; i < 500000; i += 500) { for (let i = 0; i < 50000; i += 500) {
const deltaHeight = (Random.getRandom() - 0.5) * 2000; const deltaHeight = (Random.getRandom() - 0.5) * 500;
const height = previousEnd.y + deltaHeight; const height = previousEnd.y + deltaHeight;
const currentEnd = vec2.fromValues(i, height); const currentEnd = vec2.fromValues(i, height);
const currentToRadius = Random.getRandom() * 300 + 150; const currentToRadius = Random.getRandom() * 300 + 150;

View file

@ -8,11 +8,14 @@ import {
MoveActionCommand, MoveActionCommand,
serializesTo, serializesTo,
clamp, clamp,
last,
Circle,
} from 'shared'; } from 'shared';
import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box'; import { ImmutableBoundingBox } from '../physics/bounding-boxes/immutable-bounding-box';
import { CirclePhysical } from './circle-physical'; import { CirclePhysical } from './circle-physical';
import { Physical } from '../physics/physical'; import { Physical } from '../physics/physical';
import { PhysicalContainer } from '../physics/containers/physical-container'; import { PhysicalContainer } from '../physics/containers/physical-container';
import { Spring } from './spring';
@serializesTo(CharacterBase) @serializesTo(CharacterBase)
export class CharacterPhysical extends CharacterBase implements Physical { export class CharacterPhysical extends CharacterBase implements Physical {
@ -27,6 +30,7 @@ export class CharacterPhysical extends CharacterBase implements Physical {
public rightFoot: CirclePhysical; public rightFoot: CirclePhysical;
private movementActions: Array<MoveActionCommand> = []; private movementActions: Array<MoveActionCommand> = [];
private lastMovementAction: MoveActionCommand = new MoveActionCommand(vec2.create());
protected commandExecutors: CommandExecutors = { protected commandExecutors: CommandExecutors = {
[StepCommand.type]: this.step.bind(this), [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 headOffset = vec2.fromValues(0, 40);
private static readonly leftFootOffset = vec2.fromValues(-20, -10); private static readonly leftFootOffset = vec2.fromValues(-20, -35);
private static readonly rightFootOffset = vec2.fromValues(20, -10); private static readonly rightFootOffset = vec2.fromValues(20, -35);
constructor(private readonly container: PhysicalContainer) { constructor(private readonly container: PhysicalContainer) {
super(id(), undefined, undefined, undefined); super(id());
this.head = new CirclePhysical( this.head = new CirclePhysical(
vec2.clone(CharacterPhysical.headOffset), vec2.clone(CharacterPhysical.headOffset),
50, 50,
@ -76,6 +80,10 @@ export class CharacterPhysical extends CharacterBase implements Physical {
return this; return this;
} }
public get center(): vec2 {
return this.head.center;
}
public distance(target: vec2): number { public distance(target: vec2): number {
return ( return (
Math.min( Math.min(
@ -87,92 +95,82 @@ export class CharacterPhysical extends CharacterBase implements Physical {
} }
private sumAndResetMovementActions(): vec2 { private sumAndResetMovementActions(): vec2 {
let direction: vec2;
if (this.movementActions.length === 0) { 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( return direction;
(sum, current) => vec2.add(sum, sum, current.delta),
vec2.create(),
);
vec2.scale(movementForce, movementForce, 1 / this.movementActions.length);
this.movementActions = [];
return movementForce;
} }
public step(c: StepCommand) { public step(c: StepCommand) {
const deltaTime = c.deltaTimeInMiliseconds; const deltaTime = c.deltaTimeInMiliseconds / 1000;
this.head.applyForce(settings.gravitationalForce, deltaTime);
this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
const movementForce = this.sumAndResetMovementActions();
const direction = this.sumAndResetMovementActions();
const isAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne; const isAirborne = this.leftFoot.isAirborne && this.rightFoot.isAirborne;
if (isAirborne) { this.jumpEnergyLeft += isAirborne ? -deltaTime : deltaTime;
this.jumpEnergyLeft -= deltaTime; this.jumpEnergyLeft = clamp(this.jumpEnergyLeft, 0, settings.defaultJumpEnergy);
} else {
this.jumpEnergyLeft = settings.defaultJumpEnergy;
}
const xMax = deltaTime * settings.maxAccelerationX;
const yMax = this.jumpEnergyLeft > 0 ? deltaTime * settings.maxAccelerationY : 0;
vec2.set( const xMax = deltaTime * settings.maxAccelerationX;
movementForce, const yMax = this.jumpEnergyLeft > 0 ? settings.maxAccelerationY : 0;
clamp(movementForce.x, -xMax, xMax), const movementForce = vec2.multiply(
clamp(movementForce.y, -yMax, yMax), 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.head.applyForce(movementForce, deltaTime);
this.leftFoot.applyForce(movementForce, deltaTime); this.leftFoot.applyForce(movementForce, deltaTime);
this.rightFoot.applyForce(movementForce, deltaTime); this.rightFoot.applyForce(movementForce, deltaTime);
const bodyCenter = vec2.subtract( this.head.applyForce(settings.gravitationalForce, deltaTime);
vec2.create(), this.leftFoot.applyForce(settings.gravitationalForce, deltaTime);
this.head.center, this.rightFoot.applyForce(settings.gravitationalForce, deltaTime);
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.step(deltaTime); this.head.step(deltaTime);
this.leftFoot.step(deltaTime); this.leftFoot.step(deltaTime);

View file

@ -62,7 +62,7 @@ export class CirclePhysical implements Circle, Physical {
return vec2.distance(target, this.center) - this.radius; 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; 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; this._boundingBox.yMax = this.center.y + this._radius;
} }
public applyForce(force: vec2, timeInMilliseconds: number) { public applyForce(force: vec2, timeInSeconds: number) {
vec2.add( vec2.add(
this.velocity, this.velocity,
this.velocity, this.velocity,
vec2.scale(vec2.create(), force, timeInMilliseconds), vec2.scale(vec2.create(), force, timeInSeconds),
); );
vec2.set( vec2.set(
this.velocity, this.velocity,
clamp(this.velocity.x, -settings.maxVelocityX, settings.maxVelocityX), 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(); this.velocity = vec2.create();
} }
public step(timeInMilliseconds: number): boolean { public step(deltaTimeInSeconds: number): boolean {
vec2.scale( vec2.scale(
this.velocity, this.velocity,
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 distanceLength = vec2.length(distance);
const stepCount = Math.ceil(distanceLength / settings.physicsMaxStep); const stepCount = Math.ceil(distanceLength / settings.physicsMaxStep);
vec2.scale(distance, distance, 1 / stepCount); vec2.scale(distance, distance, 1 / stepCount);
@ -127,13 +128,20 @@ export class CirclePhysical implements Circle, Physical {
let wasHit = false; let wasHit = false;
for (let i = 0; i < stepCount; i++) { for (let i = 0; i < stepCount; i++) {
const { normal, tangent, hitSurface } = moveCircle( const { tangent, hitSurface } = moveCircle(
this, this,
distance, vec2.clone(distance),
this.container.findIntersecting(this.boundingBox), this.container.findIntersecting(this.boundingBox),
); );
if (hitSurface) { if (hitSurface) {
vec2.scale(this.velocity, tangent!, vec2.dot(tangent!, this.velocity)); vec2.scale(this.velocity, tangent!, vec2.dot(tangent!, this.velocity));
if (
vec2.length(this.velocity) <
settings.frictionMinVelocity * deltaTimeInSeconds
) {
this.velocity = vec2.create();
}
wasHit = true; wasHit = true;
} }
} }

View 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);
}
}
}

View file

@ -73,10 +73,11 @@ export const moveCircle = (
circle.center = vec2.add(circle.center, circle.center, approxNormal); circle.center = vec2.add(circle.center, circle.center, approxNormal);
vec2.normalize(approxNormal, approxNormal);
return { return {
realDelta: delta, realDelta: delta,
hitSurface: true, hitSurface: true,
normal: vec2.normalize(approxNormal, approxNormal), normal: approxNormal,
tangent: rotate90Deg(approxNormal), tangent: rotate90Deg(approxNormal),
}; };
}; };

View file

@ -6,11 +6,13 @@ import {
DeleteObjectsCommand, DeleteObjectsCommand,
MoveActionCommand, MoveActionCommand,
serialize, serialize,
SetViewAreaActionCommand,
TransportEvents, TransportEvents,
UpdateObjectsCommand, UpdateObjectsCommand,
StepCommand, StepCommand,
SetAspectRatioActionCommand,
calculateViewArea,
} from 'shared'; } from 'shared';
import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds';
import { CharacterPhysical } from '../objects/character-physical'; import { CharacterPhysical } from '../objects/character-physical';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box'; import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
@ -19,16 +21,31 @@ import { Physical } from '../physics/physical';
export class Player extends CommandReceiver { export class Player extends CommandReceiver {
private character: CharacterPhysical; private character: CharacterPhysical;
private aspectRatio: number = 16 / 9;
private isActive = true;
private objectsPreviouslyInViewArea: Array<Physical> = []; private objectsPreviouslyInViewArea: Array<Physical> = [];
private objectsInViewArea: 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 = { protected commandExecutors: CommandExecutors = {
[StepCommand.type]: this.sendObjects.bind(this), [StepCommand.type]: this.sendObjects.bind(this),
[SetViewAreaActionCommand.type]: this.setViewArea.bind(this), [SetAspectRatioActionCommand.type]: (v: SetAspectRatioActionCommand) =>
[MoveActionCommand.type]: (c: MoveActionCommand) => { (this.aspectRatio = v.aspectRatio),
this.character.sendCommand(c); [MoveActionCommand.type]: (c: MoveActionCommand) => this.character.sendCommand(c),
},
}; };
constructor( constructor(
@ -47,18 +64,24 @@ export class Player extends CommandReceiver {
serialize(new CreatePlayerCommand(this.character)), serialize(new CreatePlayerCommand(this.character)),
); );
socket.on(
TransportEvents.Pong,
() => (this._latency = getTimeInMilliseconds() - this.pingTime!),
);
this.measureLatency();
this.sendObjects(); 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() { 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( const newlyIntersecting = this.objectsInViewArea.filter(
(o) => !this.objectsPreviouslyInViewArea.includes(o), (o) => !this.objectsPreviouslyInViewArea.includes(o),
); );
@ -103,6 +126,7 @@ export class Player extends CommandReceiver {
} }
public destroy() { public destroy() {
this.isActive = false;
this.character.destroy(); this.character.destroy();
this.objects.removeObject(this.character); this.objects.removeObject(this.character);
} }

View file

@ -1,17 +0,0 @@
{
"compilerOptions": {
"outDir": "dist",
"sourceMap": true,
"target": "es5",
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"strict": true,
"experimentalDecorators": true,
"downlevelIteration": true,
"moduleResolution": "node",
"module": "commonjs",
"composite": true,
"lib": ["dom", "es2017"]
}
}

View file

@ -1,21 +0,0 @@
{
"folders": [
{
"name": "Root",
"path": "."
},
{
"name": "Frontend",
"path": "./frontend"
},
{
"name": "Backend",
"path": "./backend"
},
{
"name": "Shared",
"path": "./shared"
}
],
"settings": {}
}

View file

@ -10,15 +10,17 @@ export class KeyboardListener extends CommandGenerator {
target.addEventListener('keydown', (event: KeyboardEvent) => { target.addEventListener('keydown', (event: KeyboardEvent) => {
const key = this.normalize(event.key); const key = this.normalize(event.key);
this.keysDown.add(key); this.keysDown.add(key);
this.generateCommands();
}); });
target.addEventListener('keyup', (event: KeyboardEvent) => { target.addEventListener('keyup', (event: KeyboardEvent) => {
const key = this.normalize(event.key); const key = this.normalize(event.key);
this.keysDown.delete(key); this.keysDown.delete(key);
this.generateCommands();
}); });
} }
public generateCommands() { private generateCommands() {
const up = ~~( const up = ~~(
this.keysDown.has('w') || this.keysDown.has('w') ||
this.keysDown.has('arrowup') || this.keysDown.has('arrowup') ||
@ -31,8 +33,8 @@ export class KeyboardListener extends CommandGenerator {
const movement = vec2.fromValues(right - left, up - down); const movement = vec2.fromValues(right - left, up - down);
if (vec2.squaredLength(movement) > 0) { if (vec2.squaredLength(movement) > 0) {
vec2.normalize(movement, movement); vec2.normalize(movement, movement);
this.sendCommandToSubcribers(new MoveActionCommand(movement));
} }
this.sendCommandToSubcribers(new MoveActionCommand(movement));
} }
private normalize(key: string): string { private normalize(key: string): string {

View file

@ -9,9 +9,6 @@ import {
export class TouchListener extends CommandGenerator { export class TouchListener extends CommandGenerator {
private previousPosition = vec2.create(); private previousPosition = vec2.create();
private currentPosition = vec2.create();
private previousDeltas: Array<vec2> = [];
constructor(target: HTMLElement) { constructor(target: HTMLElement) {
super(); super();
@ -22,7 +19,6 @@ export class TouchListener extends CommandGenerator {
const touchCount = event.touches.length; const touchCount = event.touches.length;
const position = this.positionFromEvent(event); const position = this.positionFromEvent(event);
this.previousPosition = position; this.previousPosition = position;
this.currentPosition = position;
if (touchCount == 1) { if (touchCount == 1) {
this.sendCommandToSubcribers(new PrimaryActionCommand(position)); this.sendCommandToSubcribers(new PrimaryActionCommand(position));
@ -37,24 +33,20 @@ export class TouchListener extends CommandGenerator {
event.preventDefault(); event.preventDefault();
const position = this.positionFromEvent(event); const position = this.positionFromEvent(event);
this.previousDeltas.push( const movement = vec2.subtract(vec2.create(), position, this.previousPosition);
vec2.subtract(vec2.create(), position, this.previousPosition),
);
this.currentPosition = position;
});
}
public generateCommands() { if (vec2.squaredLength(movement) > 0) {
const movement = vec2.subtract( vec2.normalize(movement, movement);
vec2.create(), this.sendCommandToSubcribers(new MoveActionCommand(movement));
this.currentPosition, }
this.previousPosition,
); this.previousPosition = position;
this.previousPosition = this.currentPosition; });
if (vec2.squaredLength(movement) > 0) {
vec2.normalize(movement, movement); target.addEventListener('touchend', (event: TouchEvent) => {
this.sendCommandToSubcribers(new MoveActionCommand(movement)); event.preventDefault();
} this.sendCommandToSubcribers(new MoveActionCommand(vec2.create()));
});
} }
private positionFromEvent(event: TouchEvent): vec2 { private positionFromEvent(event: TouchEvent): vec2 {

View file

@ -13,12 +13,13 @@ import {
import { import {
broadcastCommands, broadcastCommands,
deserialize, deserialize,
prettyPrint,
serialize, serialize,
settings, settings,
SetViewAreaActionCommand,
StepCommand, StepCommand,
TransportEvents, TransportEvents,
} from 'shared'; } from 'shared';
import { SetAspectRatioActionCommand } from 'shared/src/main';
import io from 'socket.io-client'; import io from 'socket.io-client';
import { KeyboardListener } from './commands/generators/keyboard-listener'; import { KeyboardListener } from './commands/generators/keyboard-listener';
import { MouseListener } from './commands/generators/mouse-listener'; import { MouseListener } from './commands/generators/mouse-listener';
@ -33,14 +34,14 @@ import { GameObjectContainer } from './objects/game-object-container';
import { BlobShape } from './shapes/blob-shape'; import { BlobShape } from './shapes/blob-shape';
export class Game { export class Game {
public readonly gameObjects = new GameObjectContainer(); public readonly gameObjects = new GameObjectContainer(this);
private readonly canvas: HTMLCanvasElement = document.querySelector('canvas#main'); private readonly canvas: HTMLCanvasElement = document.querySelector(
private renderer: Renderer; 'canvas#main',
private socket: SocketIOClient.Socket; ) as HTMLCanvasElement;
private renderer!: Renderer;
private socket!: SocketIOClient.Socket;
private deltaTimeCalculator = new DeltaTimeCalculator(); private deltaTimeCalculator = new DeltaTimeCalculator();
private overlay: HTMLElement = document.querySelector('#overlay'); private overlay: HTMLElement = document.querySelector('#overlay') as HTMLDivElement;
private keyboardListener: KeyboardListener;
private touchListener: TouchListener;
private async setupCommunication(): Promise<void> { private async setupCommunication(): Promise<void> {
await Configuration.initialize(); await Configuration.initialize();
@ -56,17 +57,21 @@ export class Game {
this.socket.on(TransportEvents.ServerToPlayer, (serialized: string) => { this.socket.on(TransportEvents.ServerToPlayer, (serialized: string) => {
const command = deserialize(serialized); const command = deserialize(serialized);
//console.log(command);
this.gameObjects.sendCommand(command); this.gameObjects.sendCommand(command);
}); });
this.socket.on(TransportEvents.Ping, () => {
this.socket.emit(TransportEvents.Pong);
});
this.socket.emit(TransportEvents.PlayerJoining, null); this.socket.emit(TransportEvents.PlayerJoining, null);
this.keyboardListener = new KeyboardListener(document.body);
this.touchListener = new TouchListener(this.canvas);
broadcastCommands( broadcastCommands(
[this.keyboardListener, new MouseListener(this.canvas), this.touchListener], [
new KeyboardListener(document.body),
new MouseListener(this.canvas),
new TouchListener(this.canvas),
],
[this.gameObjects, new CommandReceiverSocket(this.socket)], [this.gameObjects, new CommandReceiverSocket(this.socket)],
); );
} }
@ -140,36 +145,21 @@ export class Game {
return this.renderer.displayToWorldCoordinates(p); return this.renderer.displayToWorldCoordinates(p);
} }
public aspectRatioChanged(aspectRatio: number) {
this.socket.emit(
TransportEvents.PlayerToServer,
serialize(new SetAspectRatioActionCommand(aspectRatio)),
);
}
private gameLoop(time: DOMHighResTimeStamp) { private gameLoop(time: DOMHighResTimeStamp) {
const deltaTime = this.deltaTimeCalculator.getNextDeltaTimeInMilliseconds(time); const deltaTime = this.deltaTimeCalculator.getNextDeltaTimeInMilliseconds(time);
this.keyboardListener.generateCommands();
this.touchListener.generateCommands();
if (this.gameObjects.camera) {
// todo: Should only send aspect ratio
this.socket.emit(
TransportEvents.PlayerToServer,
serialize(new SetViewAreaActionCommand(this.gameObjects.camera.viewArea)),
);
}
this.gameObjects.sendCommand(new StepCommand(deltaTime)); this.gameObjects.sendCommand(new StepCommand(deltaTime));
/*this.camera.sendCommand(new MoveToCommand(this.character.position)); this.gameObjects.sendCommand(new RenderCommand(this.renderer));
this.camera.sendCommand(new RenderCommand(this.renderer));*/
/*const shouldBeDrawn = this.physics
.findIntersecting(this.camera.viewArea)
.map((b) => b.owner);
for (const object of shouldBeDrawn) {
object?.sendCommand(new RenderCommand(this.renderer));
}*/
this.gameObjects.sendCommand(new RenderCommand(this.renderer) as any);
this.renderer.renderDrawables(); this.renderer.renderDrawables();
//this.overlay.innerText = prettyPrint(this.renderer.insights); this.overlay.innerText = prettyPrint(this.renderer.insights);
requestAnimationFrame(this.gameLoop.bind(this)); requestAnimationFrame(this.gameLoop.bind(this));
} }
} }

View file

@ -1,36 +1,29 @@
import { vec2 } from 'gl-matrix'; import { vec2 } from 'gl-matrix';
import { CommandExecutors, GameObject, Rectangle, settings } from 'shared'; import { calculateViewArea, CommandExecutors, GameObject } from 'shared';
import { RenderCommand } from '../commands/types/render'; import { RenderCommand } from '../commands/types/render';
import { Game } from '../game';
export class Camera extends GameObject { export class Camera extends GameObject {
private static readonly inViewAreaSize = settings.inViewAreaSize; public center: vec2 = vec2.create();
private _viewArea = new Rectangle();
private aspectRatio?: number;
protected commandExecutors: CommandExecutors = { protected commandExecutors: CommandExecutors = {
[RenderCommand.type]: this.draw.bind(this), [RenderCommand.type]: this.draw.bind(this),
}; };
constructor(public center: vec2 = vec2.create()) { constructor(private game: Game) {
super(null); super(null);
} }
public get viewArea(): Rectangle {
return this._viewArea;
}
private draw(c: RenderCommand) { private draw(c: RenderCommand) {
const canvasAspectRatio = c.renderer.canvasSize.x / c.renderer.canvasSize.y; const canvasAspectRatio = c.renderer.canvasSize.x / c.renderer.canvasSize.y;
if (canvasAspectRatio !== this.aspectRatio) {
this.aspectRatio = canvasAspectRatio;
this.game.aspectRatioChanged(canvasAspectRatio);
}
this._viewArea.topLeft = vec2.fromValues( const viewArea = calculateViewArea(this.center, canvasAspectRatio);
this.center.x - this._viewArea.size.x / 2, c.renderer.setViewArea(viewArea.topLeft, viewArea.size);
this.center.y + this._viewArea.size.y / 2,
);
this._viewArea.size = vec2.fromValues(
Math.sqrt(Camera.inViewAreaSize * canvasAspectRatio),
Math.sqrt(Camera.inViewAreaSize / canvasAspectRatio),
);
c.renderer.setViewArea(this._viewArea.topLeft, this._viewArea.size);
} }
} }

View file

@ -10,6 +10,7 @@ import {
StepCommand, StepCommand,
UpdateObjectsCommand, UpdateObjectsCommand,
} from 'shared'; } from 'shared';
import { Game } from '../game';
import { Camera } from './camera'; import { Camera } from './camera';
import { CharacterView } from './character-view'; import { CharacterView } from './character-view';
@ -21,7 +22,7 @@ export class GameObjectContainer extends CommandReceiver {
protected commandExecutors: CommandExecutors = { protected commandExecutors: CommandExecutors = {
[CreatePlayerCommand.type]: (c: CreatePlayerCommand) => { [CreatePlayerCommand.type]: (c: CreatePlayerCommand) => {
this.player = c.character as CharacterView; this.player = c.character as CharacterView;
this.camera = new Camera(); this.camera = new Camera(this.game);
this.addObject(this.player); this.addObject(this.player);
this.addObject(this.camera); this.addObject(this.camera);
}, },
@ -49,6 +50,10 @@ export class GameObjectContainer extends CommandReceiver {
}, },
}; };
constructor(private game: Game) {
super();
}
protected defaultCommandExecutor(c: Command) { protected defaultCommandExecutor(c: Command) {
this.objects.forEach((o) => o.sendCommand(c)); this.objects.forEach((o) => o.sendCommand(c));
} }

View file

@ -1,17 +0,0 @@
{
"compilerOptions": {
"outDir": "dist",
"target": "es5",
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,
"strict": true,
"experimentalDecorators": true,
"downlevelIteration": true,
"moduleResolution": "node",
"module": "es6",
"composite": true,
"lib": ["dom", "es2017"]
}
}

View file

@ -4,11 +4,11 @@ import { Command } from '../command';
@serializable @serializable
export class MoveActionCommand extends Command { export class MoveActionCommand extends Command {
public constructor(public readonly delta: vec2) { public constructor(public readonly direction: vec2) {
super(); super();
} }
public toArray(): Array<any> { public toArray(): Array<any> {
return [this.delta]; return [this.direction];
} }
} }

View file

@ -0,0 +1,13 @@
import { serializable } from '../../transport/serialization/serializable';
import { Command } from '../command';
@serializable
export class SetAspectRatioActionCommand extends Command {
public constructor(public readonly aspectRatio: number) {
super();
}
public toArray(): Array<any> {
return [this.aspectRatio];
}
}

View file

@ -1,14 +0,0 @@
import { Rectangle } from '../../helper/rectangle';
import { serializable } from '../../transport/serialization/serializable';
import { Command } from '../command';
@serializable
export class SetViewAreaActionCommand extends Command {
public constructor(public readonly viewArea: Rectangle) {
super();
}
public toArray(): Array<any> {
return [this.viewArea];
}
}

View file

@ -0,0 +1,22 @@
import { vec2 } from 'gl-matrix';
import { Rectangle, settings } from '../main';
export const calculateViewArea = (
center: vec2,
aspectRatio: number,
oversizeRatio = 1,
): Rectangle => {
const viewArea = new Rectangle();
viewArea.size = vec2.fromValues(
Math.sqrt(settings.inViewAreaSize * oversizeRatio * aspectRatio),
Math.sqrt((settings.inViewAreaSize * oversizeRatio) / aspectRatio),
);
viewArea.topLeft = vec2.fromValues(
center.x - viewArea.size.x / 2,
center.y + viewArea.size.y / 2,
);
return viewArea;
};

View file

@ -9,6 +9,10 @@ export class Circle {
return vec2.distance(this.center, target) - this.radius; return vec2.distance(this.center, target) - this.radius;
} }
public distanceBetween(target: Circle): number {
return vec2.distance(target.center, this.center) - this.radius - target.radius;
}
public toArray(): Array<any> { public toArray(): Array<any> {
return [this.center, this.radius]; return [this.center, this.radius];
} }

View file

@ -6,15 +6,18 @@ export * from './commands/types/update-objects';
export * from './commands/types/step'; export * from './commands/types/step';
export * from './commands/types/ternary-action'; export * from './commands/types/ternary-action';
export * from './commands/types/move-action'; export * from './commands/types/move-action';
export * from './commands/types/set-view-area-action'; export * from './commands/types/set-aspect-ratio-action';
export * from './commands/types/primary-action'; export * from './commands/types/primary-action';
export * from './commands/types/secondary-action'; export * from './commands/types/secondary-action';
export * from './commands/command-receiver'; export * from './commands/command-receiver';
export * from './commands/command-executors'; export * from './commands/command-executors';
export * from './commands/command-generator'; export * from './commands/command-generator';
export * from './commands/broadcast-commands'; export * from './commands/broadcast-commands';
export * from './commands/types/set-aspect-ratio-action';
export * from './helper/array'; export * from './helper/array';
export * from './helper/last';
export * from './helper/clamp'; export * from './helper/clamp';
export * from './helper/calculate-view-area';
export * from './helper/pretty-print'; export * from './helper/pretty-print';
export * from './helper/circle'; export * from './helper/circle';
export * from './helper/rectangle'; export * from './helper/rectangle';

View file

@ -5,13 +5,15 @@ export const settings = {
hitDetectionCirclePointCount: 32, hitDetectionCirclePointCount: 32,
hitDetectionMaxOverlap: 0.01, hitDetectionMaxOverlap: 0.01,
physicsMaxStep: 5, physicsMaxStep: 5,
gravitationalForce: vec2.fromValues(0, -0.0055), gravitationalForce: vec2.fromValues(0, -200),
maxVelocityX: 1, maxVelocityX: 500,
maxAccelerationX: 0.005, maxVelocityY: 750,
maxAccelerationY: 0.01, maxAccelerationX: 16000,
targetPhysicsDeltaTimeInMilliseconds: 10, maxAccelerationY: 5500,
targetPhysicsDeltaTimeInMilliseconds: 15,
minPhysicsSleepTime: 4, minPhysicsSleepTime: 4,
velocityAttenuation: 0.99, velocityAttenuation: 0.5,
frictionMinVelocity: 400,
inViewAreaSize: 1920 * 1080 * 3, inViewAreaSize: 1920 * 1080 * 3,
defaultJumpEnergy: 600, defaultJumpEnergy: 0.75,
}; };

View file

@ -1 +1 @@
export type Id = number; export type Id = number | null;

View file

@ -2,4 +2,6 @@ export enum TransportEvents {
PlayerJoining = 'PlayerJoining', PlayerJoining = 'PlayerJoining',
PlayerToServer = 'PlayerToServer', PlayerToServer = 'PlayerToServer',
ServerToPlayer = 'ServerToPlayer', ServerToPlayer = 'ServerToPlayer',
Ping = 'Ping',
Pong = 'Pong',
} }

View file

@ -1,10 +1,10 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5",
"outDir": "lib", "outDir": "lib",
"sourceMap": true, "sourceMap": true,
"declaration": true, "declaration": true,
"declarationMap": true, "declarationMap": true,
"target": "es6",
"esModuleInterop": true, "esModuleInterop": true,
"strict": true, "strict": true,
"experimentalDecorators": true, "experimentalDecorators": true,

View file

@ -1,6 +1,5 @@
{ {
"compilerOptions": { "compilerOptions": {
"outDir": "lib",
"sourceMap": true, "sourceMap": true,
"declaration": true, "declaration": true,
"declarationMap": true, "declarationMap": true,