Я создал поле и объект, который можно по нему перемещать при помощи нажатия клавиш курсора.
Демо здесь. Проблема в том, что я назначаю начальные координаты так чтобы объект оказался в середине поля, но после нажатия клавиш объект начинает движение из левого верхнего угла.
Помогите пожалуйста это исправить. То есть требуется чтобы объект двигался от середины поля а не от верхнего левого угла.
Вот код, если в песочницу лень заглядывать:
const config = {
canvasWidth: 200,
canvasHeight: 200,
canvasColor: 'lime',
playerWidth: 10,
playerHeight: 10,
playerColor: '#000',
playerInitCoords: { x: 100, y: 100 },
playerStep: 2,
}
const PLAYER_CALC_POSITION = {
37: { x: -config.playerStep, y: 0 },
39: { x: config.playerStep, y: 0 },
38: { x: 0, y: -config.playerStep },
40: { x: 0, y: config.playerStep },
};
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
canvas.width = config.canvasWidth;
canvas.height = config.canvasHeight;
function cords(currCoords, newCoords) {
return {
x: currCoords.x + newCoords.x,
y: currCoords.y + newCoords.y,
};
}
function render(coords) {
console.log(coords);
ctx.fillStyle = config.canvasColor;
ctx.fillRect(0, 0, config.canvasWidth, config.canvasHeight);
ctx.fillStyle = config.playerColor;
ctx.fillRect(coords.x, coords.y, config.playerWidth, config.playerHeight);
}
const keydown$ = Rx.Observable.fromEvent(document, 'keydown')
.map((event) => PLAYER_CALC_POSITION[event.keyCode])
.filter(direction => !!direction)
.scan(cords)
.startWith(config.playerInitCoords)
.distinctUntilChanged();
keydown$.subscribe(coords => render(coords));