Я создаю движущийся объект, игрок.
У меня есть класс InputHandler и Player, а также игровой цикл.
Однако основная проблема заключается в том, что в InputHandler я устанавливаю и получаю все ключи, изатем используйте их в классе Player.Однако, когда я нажимаю, например, W, ничего не происходит.Даже не консольный журнал, но так и должно быть.
Я не уверен, почему это не работает.
Вот GitHub: https://github.com/AurelianSpodarec/Ship_Game_Proto_V1/blob/master/src/js/gameObjects/player/Player.js
Это последняя строка, которая должна подойти, Update, оператор if, если нажата W, а затем консоль, которая выходит из системы, но это не't.
JS код:
import InputManager from "../../core/InputManager";
export default class Player {
constructor(inputManager) {
this.height = 40,
this.width = 40,
this.size = 15,
this.inputManager = new InputManager(this.player);
this.maxSpeed = 7;
this.speed = 0;
this.position = {
x: 44,
y: 44
}
}
moveUp() {
console.log(this.inputManager.keys.w);
console.log("uppppppppppppppppppppp the player! Hop Hop!");
this.position.y -= 5;
}
moveRight() {
this.position.x += 5;
}
moveDown() {
this.position.y += 5;
}
moveLeft() {
this.position.x -= 5;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.size, 0, 2 * Math.PI, false);
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();
}
update(deltaTime) {
if (this.inputManager.isKeyDown(this.inputManager.keys.w)) {
console.log("d");
this.moveUp();
}
}
}
import * as keys from '../config/Keys';
export default class InputManager {
constructor(player) {
this.keys = keys;
this.pressedKeys = {};
for (var k in keys) {
this.pressedKeys[keys[k]] = false;
}
document.addEventListener("keydown", event => {
event.preventDefault();
this.pressedKeys[event.keyCode] = true;
});
document.addEventListener("keyup", event => {
this.pressedKeys[event.keyCode] = false;
});
}
keyDown(e) {
this.pressedKeys[e.keyCode] = true;
}
keyUp(e) {
this.pressedKeys[e.keyCode] = false;
}
isKeyDown(key) {
return this.pressedKeys[key];
}
}
import Player from "./gameObjects/player/Player";
import InputManager from "./core/InputManager";
export default class Game {
constructor(gameWidth, gameHeight) {
this.gameWidth = gameWidth;
this.gameHeight = gameHeight;
this.player = new Player(this);
new InputManager(this);
}
draw(ctx) {
this.player.draw(ctx);
}
update(delta) {
this.player.update(delta);
}
start() {
}
}
import Game from './Game';
let canvas = document.getElementById("game-screen");
let ctx = canvas.getContext("2d");
const GAME_WIDTH = 800;
const GAME_HEIGHT = 600;
let game = new Game(GAME_WIDTH, GAME_HEIGHT);
let lastTime = 0;
function gameLoop(timestamp) {
let deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
game.update(deltaTime);
game.draw(ctx);
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);