Я только начинаю с javascript и создаю игру в браузере, в которой аватар можно перемещать по экрану с помощью клавиш WASD и всегда поворачивать лицом к курсору. Пока все работает как положено, но если я перемещаю аватар по экрану с помощью клавиатуры без поворота, как только я применяю поворот к изображению аватара игрока, он телепортируется обратно в положение по умолчанию на странице и не может больше перемещаться с помощью клавиш клавиатуры. Я знаю, что проблема в l ie в последнем фрагменте этого кода, где я применяю вращение к аватару, потому что, когда я закомментирую последнюю строку, он никогда не будет телепортирован обратно. Вот мой javascript:
// Gets the (x, y) position of the avatar's origin relative to top left of the screen
function getAvatarOrgPosition() {
var rect = avatar.getBoundingClientRect();
var xPos = rect.left;
var yPos = rect.top;
return {
x: xPos,
y: yPos
};
}
window.addEventListener('mousemove', rotateAvatar);
// Makes the avatar point in the direction of the cursor
function rotateAvatar(e){
var avatarX = getAvatarOrgPosition().x;
var avatarY = getAvatarOrgPosition().y;
var mouseX = getMousePosition(e).x;
var mouseY = getMousePosition(e).y;
// Finds the angle between the cursor and the avatar's position on the screen
var angle = (Math.atan((mouseY - avatarY)/(mouseX - avatarX))) * (180/Math.PI);
if(mouseX - avatarX < 0){
angle += 180;
}
var rotate = 'transform: rotate(' + angle + 'deg);';
avatar.setAttribute('style', rotate);
// Commenting out the above line fixes 'teleport' issue, but obviously doesn't allow any rotation
}
CSS:
#avatar{
width: 181px;
height: 70px;
position: absolute;
transform-origin: 10% 50%;
top: 265px;
left: 432px;
}