How to use atan2() in combination with other Radian angle systems

后端 未结 4 729
陌清茗
陌清茗 2021-02-04 18:46

I am struggling with this in JavaScript, but this problem applies to many other languages/environments as well.

I want to have one object rotating towards the position o

相关标签:
4条回答
  • 2021-02-04 19:09

    Just use the condition

     var radians = Math.atan2(e.y - cy, e.x - cx);
     if(radians < 0 ) {radians += 2*Math.PI;}
    

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext("2d");
    canvas.onmousedown = function(e){
    var rect = canvas.getBoundingClientRect();
    var cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2;
    var radians = Math.atan2(e.y - cy, e.x - cx);
    if(radians < 0 ) {radians += 2*Math.PI;}
    ctx.moveTo(cx,cy);
    ctx.lineTo(cx + 100 * Math.cos(radians), cy + 100* Math.sin(radians));
    ctx.stroke();
    };
    <canvas id="canvas" width="200px" height="200px" style="background-color: gold;"></canvas>

    0 讨论(0)
  • 2021-02-04 19:11

    If your result is between 0 and Pi, then the result is pretty straight-forward. If your result is between -Pi and 0, then add 2*Pi to your result, this way you will have your result in the interval of 0, 2*Pi.

    Of course, it would be nice if you would implement a separate function for this type of conversion, to not duplicate your code every now and then.

    0 讨论(0)
  • 2021-02-04 19:16

    The values are the same in both cases, modulo 2*PI, and with an adjustment for the different sign and offset convention. Pseudo-code:

    theta = 0.5*M_PI - atan2(y, x); // adjust for required sign/offset
    theta = fmod(theta, 2.0*M_PI);  // make result modulo 2*PI
    
    0 讨论(0)
  • 2021-02-04 19:18

    If you want the angle to increase clockwise from 0 on the y axis, calculate the angle as atan2(x,y). This however give negative angles for x<0, so you should add 2*pi in this case.

    0 讨论(0)
提交回复
热议问题