Search code examples
c++allegro5

Radian of vector perpendicular to vector


I have a vector between (posX, posY) and (mouseX, mouseY), and I get the mouse position as a positive integer with allegro's event library. From this vector using an arc tangent I get the radian of (deltaX, deltaY). I then plug that radian into an al_draw_rotated_bitmap function. I expect the bitmap to point towards where the mouse cursor is, but the issue I have is that the radian or vector is causing it to be rotated perpendicular to the cursor.

Here is the relevant code:

void setRotation(int dx, int dy)
{
    float deltax = posX - mouseX;
    float deltay = posY - mouseY;

    rotation = atan2(deltay, deltax);
}

void Player::draw()
{
    al_draw_rotated_bitmap(player, al_get_bitmap_width(player) / 2, al_get_bitmap_height(player) / 2, posX, posY, rotation, 0);

}

int main()
{
    while(true)
    {
        player.setRotation(mouseX, mouseY);
        player.draw();
        al_flip_display();
    }
}

Solution

  • Imagine (deltax, deltay) = (0, 100), that is the mouse is 100 pixels above the object, and so the picture (I believe) shouldn't be rotated at all. But atan2(deltay, deltax) = atan2(100, 0) = π/2, that's why your picture is rotated perpendicularly.

    To fix this you should change it to atan2(deltax, deltay), possibly adding - before arguments depending on the direction of X and Y axes in Allegro, which I don't know.

    In other words, atan2 measures the angle relative to X axis, but in your case the angle should be measured relative to Y axis (because alignment on Y axis means no rotation), so you should swap its arguments.