1
\$\begingroup\$

I'm building a basic game using plain javascript and I am trying to rotate my object to follow my mouse.

I've tried getting the client's mouse X and Y then subtracting the canvas width and height divided by two. Then taking those values and inputing it into Math.atan2(). However, I feel the issue may be in my transform and rotate. The code bellow is what I've tried.

WIDTH = c.height;
HEIGHT = c.width;
document.onmousemove = function(ve){
            let cX = -c.width / 2;
            let cY = -c.height / 2;
            let x = ve.offsetX;
            let y = ve.offsetY;
            var rX = cX + x - 8;
            var rY = cY + y - 8;
            player.angle = Math.atan2(rX, rY) / Math.PI * 180;
        }
function update(){
                        var now = Date.now();
                        dt = now - lastUpdate;
                        ctx.clearRect(0, 0, WIDTH, HEIGHT);
                        ctx.setTransform(1, 0, 0, 1, WIDTH / 2, HEIGHT / 2);
                        ctx.rotate(player.angle + 10);
                        drawCircle(player.x, player.y, 20, 0, 180, "red");
                        ctx.setTransform(1, 0, 0, 1, 0, 0);
}
setInterval(update, dt/10000);

The player spins around my mouse in wide circles with no apparent pattern. Here's a gif showing what's happening. https://gyazo.com/006c99879ecf219791d059de14d98b74

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You need to transform the (0;0) position of the canvas so that it lies on the center of the player, then after rotating it, draw the player at (0; 0). This is required, because every rotation gets applied around the origin.

\$\endgroup\$
3
  • \$\begingroup\$ So was that what was the weird rotation? \$\endgroup\$
    – Ameer
    Commented May 21, 2019 at 15:44
  • 1
    \$\begingroup\$ @Ameer yes, you don't draw the player to (0; 0) \$\endgroup\$
    – Bálint
    Commented May 21, 2019 at 17:24
  • \$\begingroup\$ Alrighty I'll try that out asap and get back to you \$\endgroup\$
    – Ameer
    Commented May 23, 2019 at 2:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .