我剛剛開始使用 javascript,正在制作一個瀏覽器內游戲,其中可以使用 WASD 鍵在屏幕上移動頭像,并且始終旋轉以面向光標。到目前為止,一切都按預期工作,但是如果我使用鍵盤在屏幕上移動頭像而不進行任何旋轉,那么一旦我對玩家的頭像圖像應用旋轉,它就會傳送回頁面上的默認位置,并且無法不再用鍵盤按鍵移動。我知道問題出在這段代碼的最后一個片段中,我將旋轉應用于頭像,因為當我注釋掉最后一行時,它永遠不會被傳送回來。這是我的 JavaScript:// Gets the (x, y) position of the avatar's origin relative to top left of the screenfunction 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 cursorfunction 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;}
1 回答

汪汪一只貓
TA貢獻1898條經驗 獲得超8個贊
當您嘗試應用多個 CSS 轉換時,通常會發生這種情況。您正在使用transform: rotate
輪換,并且可能transform: translate
用于該位置。
要將它們一起應用,您需要將它們設置在同一個轉換指令中,例如transform: rotate(45deg) translate(10px, 10px)
.?否則瀏覽器僅應用最后一個。
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消