Javascript 当我移动图像然后应用旋转变换时,它;“远程传送”;回到原来的位置

Javascript 当我移动图像然后应用旋转变换时,它;“远程传送”;回到原来的位置,javascript,html,css,Javascript,Html,Css,我刚开始使用javascript,正在制作一个浏览器内游戏,在这个游戏中,可以使用WASD键在屏幕上移动化身,并始终旋转以面对光标。到目前为止,一切正常,但如果我用键盘在屏幕上移动化身而不旋转,只要我对玩家的化身图像进行旋转,它就会传送回页面上的默认位置,并且不能再用键盘键移动。我知道问题在于这段代码的最后一个片段,我将旋转应用于化身,因为当我注释掉最后一行时,它永远不会被传送回来。以下是我的javascript: // Gets the (x, y) position of the avata

我刚开始使用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转换时,通常会发生这种情况。您正在使用
transform:rotate
进行旋转,并且可能将
transform:translate
用于位置

要同时应用它们,需要在相同的转换指令中设置它们,如
transform:rotate(45度)translate(10px,10px)
。否则,浏览器仅应用最后一个


如果您想要更详细的答案,请看一看。

您是否也可以发布
getAvatarOrgPosition
的定义?css是什么?欢迎访问!A会有帮助的。你可以创造一个,为什么你们要把他吐出来?他的例子非常好,而且很有说服力understandable@ezra这是可以理解的,但不足以完全诊断问题。我们想提供帮助,但我们需要更多信息!
#avatar{
    width: 181px;
    height: 70px;
    position: absolute;
    transform-origin: 10% 50%;
    top: 265px;
    left: 432px;
}