0

I'm just starting out with javascript and am making an in-browser game where an avatar can be moved around the screen with the WASD keys and always rotates to face the cursor. Everything works as expected so far, but if I move the avatar across the screen with the keyboard without any rotating, as soon as I apply a rotation to the player's avatar image, it teleports back to its default position on the page, and can no longer be moved with the keyboard keys. I know that the problem has to lie in the last snippet of this code, where I apply the rotation to the avatar, because when I comment out the last line, it never gets teleported back. Here's my 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
}

The CSS is:

#avatar{
    width: 181px;
    height: 70px;
    position: absolute;
    transform-origin: 10% 50%;
    top: 265px;
    left: 432px;
}
  • 1
    Could you also post the definition of `getAvatarOrgPosition`? – wxker Mar 07 '20 at 01:16
  • andd the css is ? – Mister Jojo Mar 07 '20 at 01:30
  • Welcome to SO! A [mcve] would be helpful. You can create a [stack snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do). – ggorlen Mar 07 '20 at 01:31
  • why are you guys chewing him out? his example is perfectly fine and understandable – ezra Mar 07 '20 at 01:34
  • 1
    @ezra It is understandable but it is insufficient to fully diagnose the problem. We want to help but we need more information! – wxker Mar 07 '20 at 01:38

1 Answers1

1

This commonly happens when you try to apply multiple CSS transforms. You're using transform: rotate for the rotation and likely transform: translate for the position.

To apply them both thogether you need to set them both in the same transform directive like transform: rotate(45deg) translate(10px, 10px). Otherwise only the last one is applied by the browser.

Have a look at this question if you want a more detailed answer.

j-petty
  • 2,668
  • 1
  • 11
  • 20