Search code examples
javascriptmathrotationpaperjsatan2

Why is Math.atan2 not working correctly for me?


I'm trying to create a simple game where the rectangle in the center always points towards the mouse. For some reason, when I use Math.atan2 I get weird values that never go above 3 for the angle...

Here's the sketch with my code

function onMouseMove(event) {
    var dx = event.point.x - view.center.x;
    var dy = event.point.y - view.center.y;
    var rotation = Math.atan2(dy, dx);

    console.log(rotation);
    player.rotation = rotation;
}

It'd be great if someone could spot what I'm doing wrong or even edit the sketch so that it works :)


Solution

  • There are three things here:

    1. Rotation adds to the current rotation with paper.js, to disable it you need to set applyMatrix: false
    2. Rotation is in degrees and not radians. you need to multiply your atan2 by 180 / Math.PI
    3. You should be using player.center and not view.center

    Here is the code you can use:

    var player = new Path.Rectangle({
        strokeColor: '#222222',
        strokeWidth: 10,
        fillColor: '#777777',
        size: [100, 80],
        center: view.center,
        applyMatrix: false
    });
    
    function onMouseMove(event) {
        var dx = event.point.x - player.center.x;
        var dy = event.point.y - player.center.y;
        var angle = Math.atan2(dy, dx) * 180 / Math.PI;
    
        console.log(angle);
        player.rotation = angle;
    }