var forwardg = 0, backwardg = 0, leftg = 0, rightg = 0;
var player = document.getElementById('player');
function addControls (forward, backward, left, right) {
document.onkeypress = function (event) {
if (event.key == forward) {
player.style.top = forwardg + 'px';
forwardg--;
console.log(event);
}
else if (event.key == backward) {
player.style.top = backwardg + 'px';
backwardg++;
console.log(event);
}
else if (event.key == left) {
player.style.left = leftg + 'px';
leftg--;
console.log(event);
}
else if (event.key == right) {
player.style.right = rightg + 'px';
rightg--;
console.log(event);
}
}
}
addControls('w', 's', 'a', 'd');
var x = 0, y = 0;
var player = document.getElementById('player');
function addControls (forward, backward, left, right) {
document.onkeypress = function (event) {
if (event.key == forward) {
y--;
player.style.top = y + 'px';
}
else if (event.key == backward) {
y++;
player.style.top = y + 'px';
console.log(event);
}
else if (event.key == left) {
x--;
player.style.left = x + 'px';
}
else if (event.key == right) {
x++;
player.style.left = x + 'px';
}
}
}
addControls('w', 's', 'a', 'd');
left
, и right
, движок теряется и не знает, что делать. Собственно, поэтому и не работает перемещение направо. Поэтому меняем только left
и top
.