Simple controlling system

This commit is contained in:
Logan Hunt 2022-04-02 18:37:36 -06:00
parent 61c835723a
commit aef3c05bc7
Signed by untrusted user who does not match committer: simponic
GPG Key ID: 52B3774857EB24B1
4 changed files with 36 additions and 3 deletions

4
src/bootstrap.js vendored
View File

@ -6,7 +6,7 @@ game.bootstrap = (() => {
{
src: [
'src/components/position.js', 'src/components/momentum.js', 'src/components/gridPosition.js',
'src/components/appearence.js'
'src/components/appearence.js', 'src/components/controllable.js'
],
id: 'components'
},
@ -24,7 +24,7 @@ game.bootstrap = (() => {
{ src: ['src/systems/system.js'], id: 'system' },
{
src: [
'src/systems/render.js', 'src/systems/gridSystem.js', 'src/systems/physics.js'
'src/systems/render.js', 'src/systems/gridSystem.js', 'src/systems/physics.js', 'src/systems/keyboardInput.js'
],
id: 'systems' },
{ src: ['src/game.js'], id: 'game' },

View File

@ -0,0 +1 @@
game.components.Controllable = ({ controls }) => game.Component('controllable', { controls });

View File

@ -11,7 +11,7 @@ game.loop = (timeStamp) => {
}
game.initialize = () => {
game.systemOrder = ["render", "physics", "gridSystem"];
game.systemOrder = ["render", "physics", "gridSystem", "keyboardInput"];
game.systems = {
render: game.system.Render(game.graphics),
physics: game.system.Physics(),
@ -21,6 +21,7 @@ game.initialize = () => {
canvasWidth: game.canvas.width,
canvasHeight: game.canvas.height,
}),
keyboardInput: game.system.KeyboardInput(),
};
game.entities = {};
@ -34,6 +35,7 @@ game.initialize = () => {
game.rock = game.createRock();
game.rock.addComponent(game.components.Position({x: 200, y: 200}));
game.rock.addComponent(game.components.GridPosition({x: 0, y: 0}));
game.rock.addComponent(game.components.Controllable({controls: ['left', 'right', 'up', 'down']}));
game.entities[game.rock.id] = game.rock;
lastTimeStamp = performance.now()

View File

@ -0,0 +1,30 @@
game.system.KeyboardInput = () => {
"use strict";
const keys = {};
const keyPress = (event) => {
if (!event.repeat) {
keys[event.key] = true;
}
};
const update = (elapsedTime, entities) => {
for (let id in entities) {
const entity = entities[id];
if (entity.hasComponent('controllable')) {
const controls = entity.components.controllable.controls;
if (controls.includes('left') && keys['ArrowLeft']) {
entity.addComponent(game.components.Momentum({ dx: -1, dy: 0 }));
} else if (controls.includes('right') && keys['ArrowRight']) {
entity.addComponent(game.components.Momentum({ dx: 1, dy: 0 }));
} else if (controls.includes('up') && keys['ArrowUp']) {
entity.addComponent(game.components.Momentum({ dx: 0, dy: -1 }));
} else if (controls.includes('down') && keys['ArrowDown']) {
entity.addComponent(game.components.Momentum({ dx: 0, dy: 1 }));
}
Object.keys(keys).map((key) => delete keys[key]);
}
}
};
window.addEventListener("keydown", keyPress);
return { keys, update };
}