Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 74074

When I move an image then apply the rotate transformation, it "teleports" back to its original position

$
0
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;
}

Viewing all articles
Browse latest Browse all 74074

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>