我刚刚开始使用 javascript,正在制作一个浏览器内游戏,其中可以使用 WASD 键在屏幕上移动头像,并且始终旋转以面向光标。到目前为止,一切都按预期工作,但是如果我使用键盘在屏幕上移动头像而不进行任何旋转,那么一旦我对玩家的头像图像应用旋转,它就会传送回页面上的默认位置,并且无法不再用键盘按键移动。我知道问题出在这段代码的最后一个片段中,我将旋转应用于头像,因为当我注释掉最后一行时,它永远不会被传送回来。这是我的 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;
}
汪汪一只猫
相关分类