DijkeMark
DijkeMark

Reputation: 1306

Rotating towards mouse in C# is not working correctly

I am trying to have an object rotate towards the mouse. The problem is that the object always rotates a bit to much to the left, an extra 45 degrees to much to be excact.

So for example if my mouse is at such a position that the object should be positioned to the north, thus the rotation value = 0, the object gets rotatated 45 degrees to the left, so 270 degrees and thus pointing left, while it should point north/upwards.

This is my code:

    public override void Update()
    {
        base.Update();

        GetMousePos();
        SetRotation();
    }

    private void GetMousePos()
    {
        MouseState ms = Mouse.GetState();
        _mousePos.X = ms.X;
        _mousePos.Y = ms.Y;
    }

    private void SetRotation()
    {
        Vector2 distance = new Vector2();
        distance.X = _mousePos.X - (_position.X + (_texture.Width / 2));
        distance.Y = _mousePos.Y - (_position.Y + (_texture.Height / 2));
        _rotation = (float)Math.Atan2(distance.Y, distance.X);
    }

EDIT: extra info

These values appear when my mouse is in the right side of the screen. The object should point east/right, but he points north/upwards.

MOUSE POS X: 1012

MOUSE POS Y: 265

OBJECT POS X: 400275

OBJECT POS Y: 24025

ROTATION: 0

EDIT 2: how _rotation is used

public virtual void Draw(SpriteBatch spriteBatch)
    {
        int width = _texture.Width / _columns;
        int height = _texture.Height / _rows;

        Rectangle destinationRectangle = new Rectangle((int)_position.X, (int)_position.Y, width, height);
        Rectangle sourceRectangle = new Rectangle((int)((_texture.Width / _columns) * _currentFrame), 0, width, height);

        spriteBatch.Begin();
        spriteBatch.Draw(_texture, destinationRectangle, sourceRectangle, Color.White, _rotation, new Vector2(width / 2, height / 2), SpriteEffects.None, 0);
        spriteBatch.End();
    }

EDIT 3: The working fix thingy

    protected void SetRotation()
    {
        MouseState mouse = Mouse.GetState();
        Vector2 mousePosition = new Vector2(mouse.X, mouse.Y);

        Vector2 direction = mousePosition - _position;
        direction.Normalize();

        _rotation = (float)Math.Atan2(
                      (double)direction.Y,
                      (double)direction.X) + 1.5f;
    }

Upvotes: 2

Views: 625

Answers (1)

D Stanley
D Stanley

Reputation: 152491

Look at the docs for Math.Atan2:

The return value is the angle in the Cartesian plane formed by the x-axis, and a vector starting from the origin, (0,0), and terminating at the point, (x,y).

So Atan2(0,1) would be pi/2, or straight up (North).

That means the measurement starts with 0 being due East (right) and rotating counterclockwise. It seems like you're expecting 0 deg. to be straight up and rotating clockwise, so you need to adjust your logic to reflect that.

Upvotes: 2

Related Questions