Add better object updates

This commit is contained in:
schmelczerandras 2020-10-17 18:35:09 +02:00
commit e83c58e1a5
9 changed files with 289 additions and 123 deletions

View file

@ -1,7 +1,13 @@
import { PhysicalContainer } from './physics/containers/physical-container';
import { Player } from './players/player';
import ioserver from 'socket.io';
import { TransportEvents, deserialize, settings, ServerInformation } from 'shared';
import {
TransportEvents,
deserialize,
settings,
ServerInformation,
PlayerInformation,
} from 'shared';
import { createWorld } from './map/create-world';
import { DeltaTimeCalculator } from './helper/delta-time-calculator';
import { Options } from './options';
@ -22,8 +28,8 @@ export class GameServer {
this.objects.initialize();
io.on('connection', (socket: SocketIO.Socket) => {
socket.on(TransportEvents.PlayerJoining, () => {
const player = new Player(this.objects, socket);
socket.on(TransportEvents.PlayerJoining, (playerInfo: PlayerInformation) => {
const player = new Player(playerInfo, this.objects, socket);
this.players.push(player);
socket.on(TransportEvents.PlayerToServer, (json: string) => {
const command = deserialize(json);

View file

@ -1,5 +1,5 @@
import { vec2 } from 'gl-matrix';
import { Circle, GameObject, serializesTo, settings } from 'shared';
import { Circle, GameObject, serializesTo, settings, UpdateObjectMessage } from 'shared';
import { PhysicalBase } from '../physics/physicals/physical-base';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
import { BoundingBoxBase } from '../physics/bounding-boxes/bounding-box-base';
@ -30,6 +30,10 @@ export class CirclePhysical implements Circle, DynamicPhysical, ReactsToCollisio
this.recalculateBoundingBox();
}
public calculateUpdates(): UpdateObjectMessage | null {
return null;
}
public get boundingBox(): BoundingBoxBase {
return this._boundingBox;
}

View file

@ -0,0 +1,318 @@
import { vec2 } from 'gl-matrix';
import {
id,
settings,
MoveActionCommand,
serializesTo,
clamp,
last,
GameObject,
Circle,
PlayerCharacterBase,
} from 'shared';
import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
import { CirclePhysical } from './circle-physical';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { BoundingBoxBase } from '../physics/bounding-boxes/bounding-box-base';
import { ProjectilePhysical } from './projectile-physical';
import { interpolateAngles } from '../helper/interpolate-angles';
import { forceAtPosition } from '../physics/functions/force-at-position';
import { getBoundingBoxOfCircle } from '../physics/functions/get-bounding-box-of-circle';
import { PlanetPhysical } from './planet-physical';
import { ReactsToCollision } from '../physics/physicals/reacts-to-collision';
import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message';
import { UpdateGameObjectMessage } from '../update-game-object-message';
@serializesTo(PlayerCharacterBase)
export class PlayerCharacterPhysical
extends PlayerCharacterBase
implements DynamicPhysical, ReactsToCollision {
public readonly canCollide = true;
public readonly canMove = true;
private static readonly headRadius = 50;
private static readonly feetRadius = 20;
// offsets are meassured from (0, 0)
private static readonly desiredHeadOffset = vec2.fromValues(0, 65);
private static readonly desiredLeftFootOffset = vec2.fromValues(-20, 0);
private static readonly desiredRightFootOffset = vec2.fromValues(20, 0);
private static readonly centerOfMass = vec2.scale(
vec2.create(),
vec2.add(
vec2.create(),
vec2.add(
vec2.create(),
PlayerCharacterPhysical.desiredHeadOffset,
PlayerCharacterPhysical.desiredLeftFootOffset,
),
PlayerCharacterPhysical.desiredRightFootOffset,
),
1 / 3,
);
private static readonly headOffset = vec2.subtract(
vec2.create(),
PlayerCharacterPhysical.desiredHeadOffset,
PlayerCharacterPhysical.centerOfMass,
);
private static readonly leftFootOffset = vec2.subtract(
vec2.create(),
PlayerCharacterPhysical.desiredLeftFootOffset,
PlayerCharacterPhysical.centerOfMass,
);
private static readonly rightFootOffset = vec2.subtract(
vec2.create(),
PlayerCharacterPhysical.desiredRightFootOffset,
PlayerCharacterPhysical.centerOfMass,
);
public static readonly boundRadius =
(PlayerCharacterPhysical.headRadius + PlayerCharacterPhysical.feetRadius * 2) * 2;
private isDestroyed = false;
private direction = 0;
private currentPlanet?: PlanetPhysical;
private lastMovementWasRelative = false;
private secondsSinceOnSurface = 1000;
public head: CirclePhysical;
public leftFoot: CirclePhysical;
public rightFoot: CirclePhysical;
public bound: CirclePhysical;
public get isAlive(): boolean {
return !this.isDestroyed;
}
private movementActions: Array<MoveActionCommand> = [];
private lastMovementAction: MoveActionCommand = new MoveActionCommand(
vec2.create(),
false,
);
constructor(
name: string,
public readonly colorIndex: number,
private readonly container: PhysicalContainer,
startPosition: vec2,
) {
super(id(), name, colorIndex);
this.head = new CirclePhysical(
vec2.add(vec2.create(), startPosition, PlayerCharacterPhysical.headOffset),
PlayerCharacterPhysical.headRadius,
this,
container,
);
this.leftFoot = new CirclePhysical(
vec2.add(vec2.create(), startPosition, PlayerCharacterPhysical.leftFootOffset),
PlayerCharacterPhysical.feetRadius,
this,
container,
);
this.rightFoot = new CirclePhysical(
vec2.add(vec2.create(), startPosition, PlayerCharacterPhysical.rightFootOffset),
PlayerCharacterPhysical.feetRadius,
this,
container,
);
container.addObject(this.head);
container.addObject(this.leftFoot);
container.addObject(this.rightFoot);
this.bound = new CirclePhysical(
vec2.create(),
PlayerCharacterPhysical.boundRadius,
this,
container,
);
}
public calculateUpdates(): UpdateObjectMessage {
return new UpdateGameObjectMessage(this, ['head', 'leftFoot', 'rightFoot']);
}
public handleMovementAction(c: MoveActionCommand) {
this.movementActions.push(c);
}
public onCollision(other: GameObject) {
if (other instanceof ProjectilePhysical) {
other.destroy();
this.destroy();
}
}
public get boundingBox(): BoundingBoxBase {
this.bound.center = this.head.center;
return this.bound.boundingBox;
}
public get gameObject(): this {
return this;
}
public get center(): vec2 {
return this.head.center;
}
public get velocity(): vec2 {
return this.head.velocity;
}
public distance(target: vec2): number {
return (
Math.min(
this.head.distance(target),
this.leftFoot.distance(target),
this.rightFoot.distance(target),
) - 20
);
}
private averageAndResetMovementActions(): vec2 {
let direction: vec2;
if (this.movementActions.length === 0) {
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.lastMovementWasRelative =
this.movementActions.find((a) => a.isCharacterRelative) !== undefined;
this.lastMovementAction = last(this.movementActions)!;
this.movementActions = [];
}
return direction;
}
public step(deltaTime: number) {
if ((this.secondsSinceOnSurface += deltaTime) > 1) {
this.currentPlanet = undefined;
}
const intersectingWithForcefield = this.container.findIntersecting(
getBoundingBoxOfCircle(
new Circle(
this.center,
PlayerCharacterPhysical.boundRadius + settings.maxGravityDistance,
),
),
);
const actualGravity = forceAtPosition(this.center, intersectingWithForcefield);
const direction = this.averageAndResetMovementActions();
const movementForce = vec2.scale(direction, direction, settings.maxAcceleration);
if (!this.currentPlanet) {
this.applyForce(this.leftFoot, actualGravity, deltaTime);
this.applyForce(this.rightFoot, actualGravity, deltaTime);
const sumForce = vec2.subtract(vec2.create(), actualGravity, movementForce);
this.setDirection(
vec2.length(sumForce) === 0 ? vec2.fromValues(0, -1) : sumForce,
deltaTime,
);
} else {
const leftFootGravity = this.currentPlanet!.getForce(this.leftFoot.center);
const rightFootGravity = this.currentPlanet!.getForce(this.rightFoot.center);
if (movementForce.y > settings.maxAcceleration / 4) {
vec2.scale(leftFootGravity, leftFootGravity, 0.35);
vec2.scale(rightFootGravity, rightFootGravity, 0.35);
}
this.applyForce(this.leftFoot, leftFootGravity, deltaTime);
this.applyForce(this.rightFoot, rightFootGravity, deltaTime);
if (this.lastMovementWasRelative) {
vec2.rotate(movementForce, movementForce, vec2.create(), this.direction);
}
const headGravity = this.currentPlanet!.getForce(this.head.center);
if (vec2.length(headGravity) < vec2.length(actualGravity) / 2) {
this.currentPlanet = undefined;
}
this.setDirection(headGravity, deltaTime);
}
this.applyForce(this.leftFoot, movementForce, deltaTime);
this.applyForce(this.rightFoot, movementForce, deltaTime);
this.stepBodyPart(this.leftFoot, deltaTime);
this.stepBodyPart(this.rightFoot, deltaTime);
this.keepPosture();
}
private setDirection(direction: vec2, deltaTime: number) {
this.direction = interpolateAngles(
this.direction,
Math.atan2(direction.y, direction.x) + Math.PI / 2,
Math.pow(4, deltaTime),
);
}
private keepPosture() {
const bodyCenter = vec2.add(vec2.create(), this.head.center, this.leftFoot.center);
vec2.add(bodyCenter, bodyCenter, this.rightFoot.center);
vec2.scale(bodyCenter, bodyCenter, 1 / 3);
this.springMove(this.leftFoot, bodyCenter, PlayerCharacterPhysical.leftFootOffset);
this.springMove(this.rightFoot, bodyCenter, PlayerCharacterPhysical.rightFootOffset);
this.springMove(this.head, bodyCenter, PlayerCharacterPhysical.headOffset);
}
private springMove(object: CirclePhysical, center: vec2, offset: vec2) {
// todo: make time-independent
const springConstant = 0.35;
const desiredPosition = vec2.add(vec2.create(), center, offset);
vec2.rotate(desiredPosition, desiredPosition, center, this.direction);
const positionDelta = vec2.subtract(desiredPosition, desiredPosition, object.center);
vec2.scale(positionDelta, positionDelta, springConstant);
const hitObject = object.tryMove(positionDelta);
if (hitObject instanceof PlanetPhysical) {
this.secondsSinceOnSurface = 0;
this.currentPlanet = hitObject;
}
}
private stepBodyPart(part: CirclePhysical, deltaTime: number) {
const hitObject = part.step2(deltaTime);
if (hitObject instanceof PlanetPhysical) {
this.secondsSinceOnSurface = 0;
this.currentPlanet = hitObject;
}
}
public applyForce(circle: CirclePhysical, force: vec2, timeInSeconds: number) {
vec2.add(
circle.velocity,
circle.velocity,
vec2.scale(vec2.create(), force, timeInSeconds),
);
vec2.set(
circle.velocity,
clamp(circle.velocity.x, -settings.maxVelocityX, settings.maxVelocityX),
clamp(circle.velocity.y, -settings.maxVelocityY, settings.maxVelocityY),
);
}
public destroy() {
if (!this.isDestroyed) {
this.isDestroyed = true;
this.container.removeObject(this);
this.container.removeObject(this.head);
this.container.removeObject(this.leftFoot);
this.container.removeObject(this.rightFoot);
}
}
}

View file

@ -6,6 +6,8 @@ import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { PlanetPhysical } from './planet-physical';
import { ReactsToCollision } from '../physics/physicals/reacts-to-collision';
import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message';
import { UpdateGameObjectMessage } from '../update-game-object-message';
@serializesTo(ProjectileBase)
export class ProjectilePhysical
@ -15,6 +17,7 @@ export class ProjectilePhysical
public readonly canMove = true;
private isDestroyed = false;
private bounceCount = 0;
private _boundingBox?: ImmutableBoundingBox;
public object: CirclePhysical;
@ -28,7 +31,9 @@ export class ProjectilePhysical
this.object = new CirclePhysical(center, radius, this, container, 0.9);
}
private _boundingBox?: ImmutableBoundingBox;
public calculateUpdates(): UpdateObjectMessage {
return new UpdateGameObjectMessage(this, ['center']);
}
public get boundingBox(): ImmutableBoundingBox {
if (!this._boundingBox) {

View file

@ -1,4 +1,4 @@
import { DynamicPhysical } from '../dynamic-physical';
import { DynamicPhysical } from '../physicals/dynamic-physical';
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
export class BoundingBoxList {

View file

@ -1,5 +1,5 @@
import { BoundingBoxBase } from '../bounding-boxes/bounding-box-base';
import { StaticPhysical } from './static-physical';
import { StaticPhysical } from '../physicals/static-physical';
// source: https://github.com/ubilabs/kd-tree-javascript/blob/master/kdTree.js
class Node {

View file

@ -1,6 +1,9 @@
import { UpdateObjectMessage } from 'shared/lib/src/objects/update-object-message';
import { PhysicalBase } from './physical-base';
export interface DynamicPhysical extends PhysicalBase {
readonly canMove: true;
step(deltaTimeInMilliseconds: number): void;
calculateUpdates(): UpdateObjectMessage | null;
}

View file

@ -14,27 +14,28 @@ import {
SecondaryActionCommand,
settings,
Circle,
PlayerInformation,
} from 'shared';
import { getTimeInMilliseconds } from '../helper/get-time-in-milliseconds';
import { CharacterPhysical } from '../objects/character-physical';
import { ProjectilePhysical } from '../objects/projectile-physical';
import { BoundingBox } from '../physics/bounding-boxes/bounding-box';
import { PhysicalContainer } from '../physics/containers/physical-container';
import { PhysicalBase } from '../physics/physicals/physical-base';
import { getBoundingBoxOfCircle } from '../physics/functions/get-bounding-box-of-circle';
import { isCircleIntersecting } from '../physics/functions/is-circle-intersecting';
import { requestColor, freeColor } from './player-color-service';
import { PlayerCharacterPhysical } from '../objects/player-character-physical';
import { DynamicPhysical } from '../physics/physicals/dynamic-physical';
import { Physical } from '../physics/physicals/physical';
export class Player extends CommandReceiver {
private character: CharacterPhysical;
private character: PlayerCharacterPhysical;
private aspectRatio: number = 16 / 9;
private isActive = true;
private timeSinceLastProjectile = 0;
private objectsPreviouslyInViewArea: Array<PhysicalBase> = [];
private objectsInViewArea: Array<PhysicalBase> = [];
private objectsPreviouslyInViewArea: Array<Physical> = [];
private objectsInViewArea: Array<Physical> = [];
private pingTime?: number;
private _latency?: number;
@ -56,7 +57,10 @@ export class Player extends CommandReceiver {
[MoveActionCommand.type]: (c: MoveActionCommand) =>
this.character.handleMovementAction(c),
[SecondaryActionCommand.type]: (c: SecondaryActionCommand) => {
if (this.timeSinceLastProjectile < settings.projectileCreationInterval) {
if (
!this.character.isAlive ||
this.timeSinceLastProjectile < settings.projectileCreationInterval
) {
return;
}
@ -88,7 +92,7 @@ export class Player extends CommandReceiver {
const playerBoundingCircle = new Circle(
playerPosition,
CharacterPhysical.boundRadius,
PlayerCharacterPhysical.boundRadius,
);
const playerBoundingBox = getBoundingBoxOfCircle(playerBoundingCircle);
@ -97,27 +101,26 @@ export class Player extends CommandReceiver {
return playerPosition;
}
rotation += Math.PI / 12;
radius += 10;
rotation += Math.PI / 8;
radius += 30;
}
}
constructor(
playerInfo: PlayerInformation,
private readonly objects: PhysicalContainer,
private readonly socket: SocketIO.Socket,
) {
super();
const colorIndex = requestColor();
this.character = new CharacterPhysical(
this.character = new PlayerCharacterPhysical(
playerInfo.name,
colorIndex,
objects,
this.findEmptyPositionForPlayer(),
);
this.objectsPreviouslyInViewArea.push(this.character);
this.objectsInViewArea.push(this.character);
this.objects.addObject(this.character);
socket.emit(
@ -138,6 +141,7 @@ export class Player extends CommandReceiver {
this.sendObjects();
this.timeSinceLastProjectile += deltaTime;
}
public sendObjects() {
const viewArea = calculateViewArea(this.character.center, this.aspectRatio, 1.5);
const bb = new BoundingBox();
@ -161,7 +165,11 @@ export class Player extends CommandReceiver {
TransportEvents.ServerToPlayer,
serialize(
new DeleteObjectsCommand([
...new Set(noLongerIntersecting.map((p) => p.gameObject.id)),
...new Set(
noLongerIntersecting
.filter((p) => p.gameObject !== this.character)
.map((p) => p.gameObject.id),
),
]),
),
);
@ -172,20 +180,25 @@ export class Player extends CommandReceiver {
TransportEvents.ServerToPlayer,
serialize(
new CreateObjectsCommand([
...new Set(newlyIntersecting.map((p) => p.gameObject)),
...new Set(
newlyIntersecting
.map((p) => p.gameObject)
.filter((g) => g !== this.character),
),
]),
),
);
}
this.socket.volatile.emit(
this.socket.emit(
TransportEvents.ServerToPlayer,
serialize(
new UpdateObjectsCommand([
...new Set(
this.objectsInViewArea.filter((p) => p.canMove).map((p) => p.gameObject),
),
]),
new UpdateObjectsCommand(
Array.from(new Set(this.objectsInViewArea))
.filter((p) => p.canMove)
.map((p) => (p as DynamicPhysical).calculateUpdates())
.filter((p) => p !== null) as any,
),
),
);
}

View file

@ -0,0 +1,11 @@
import { GameObject, serializesTo, UpdateMessage, UpdateObjectMessage } from 'shared';
@serializesTo(UpdateObjectMessage)
export class UpdateGameObjectMessage<T extends GameObject> extends UpdateObjectMessage {
constructor(object: T, keys: Array<string & keyof T>) {
super(
object.id,
keys.map((k) => new UpdateMessage(k, object[k])),
);
}
}