0

我刚开始使用 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;
}
4

1 回答 1

1

当您尝试应用多个 CSS 转换时,通常会发生这种情况。您正在使用transform: rotate旋转,并且可能transform: translate用于位置。

要同时应用它们,您需要将它们都设置在相同的转换指令中,例如transform: rotate(45deg) translate(10px, 10px). 否则浏览器只会应用最后一个。

如果您想要更详细的答案,请查看此问题。

于 2020-03-07T01:38:34.363 回答