refactor: InputPacket

This commit is contained in:
cha0s 2019-04-13 19:16:42 -05:00
parent 1066d096e8
commit 68eba007f9
5 changed files with 51 additions and 11 deletions

View File

@ -141,21 +141,36 @@ const socket = createClient(window.location.href, {
// Mouse/touch movement.
const pointerMovementHandle = setInterval(() => {
do {
let normal;
if (isPointingAtAnything()) {
const normal = createMoveToNormal(pointingAt);
normal = createMoveToNormal(pointingAt);
if (normal) {
actionRegistry.state = actionRegistry.state.set('MoveTo', normal);
actionRegistry.state = actionRegistry.state.withMutations((state) => {
if (normal[0]) {
state.set('MoveToX', Math.floor(normal[0] * 127));
}
if (normal[1]) {
state.set('MoveToY', Math.floor(normal[1] * 127));
}
});
break;
}
}
actionRegistry.state = actionRegistry.state.delete('MoveTo');
actionRegistry.state = actionRegistry.state.withMutations((state) => {
if (!normal || 0 === normal[0]) {
state.delete('MoveToX');
}
if (!normal || 0 === normal[1]) {
state.delete('MoveToY');
}
});
} while (false);
}, 1000 / 15);
// Input messages.
const inputHandle = setInterval(() => {
if (actionState !== actionRegistry.state) {
actionState = actionRegistry.state;
socket.send(new InputPacket(msgpack.encode(actionRegistry.state.toJS())));
socket.send(InputPacket.fromState(actionState));
}
}, 1000 / 60);
// Prediction.

View File

@ -1,3 +1,5 @@
import * as I from 'immutable';
import {Packet} from '@avocado/packet';
export class InputPacket extends Packet {
@ -5,8 +7,30 @@ export class InputPacket extends Packet {
static get schema() {
return {
...super.schema,
data: 'buffer',
data: [
['string'],
['varint'],
],
};
}
static fromState(state) {
const data = [[], []];
const [actions, values] = data;
for (const [action, value] of state.entries()) {
actions.push(action);
values.push(parseInt(value));
}
return new InputPacket(data);
}
toState() {
const [actions, values] = this.data;
return I.Map().withMutations((state) => {
for (let i = 0; i < actions.length; ++i) {
state.set(actions[i], values[i]);
}
});
}
}

View File

@ -7,7 +7,7 @@ export class KeysPacket extends Packet {
...super.schema,
data: [
['string'],
['uint32'],
['varuint'],
],
};
}

View File

@ -53,7 +53,7 @@ function createPacketListener(socket) {
const {entity} = socket;
return (packet) => {
if (packet instanceof InputPacket) {
entity.inputState = msgpack.decode(packet.data);
entity.inputState = packet.toState();
}
};
}

View File

@ -20,10 +20,11 @@ export class Controllable extends Trait {
return;
}
const movementVector = [0, 0];
if (inputState.has('MoveTo')) {
const moveTo = inputState.get('MoveTo');
movementVector[0] = moveTo[0];
movementVector[1] = moveTo[1];
if (inputState.has('MoveToX')) {
movementVector[0] = inputState.get('MoveToX') / 127;
}
if (inputState.has('MoveToY')) {
movementVector[1] = inputState.get('MoveToY') / 127;
}
if (inputState.has('MoveUp')) {
movementVector[1] -= 1;