2

オブジェクトをマウスに向かって回転させようとしています。問題は、オブジェクトが常に少し左に回転することです。正確には、余分に 45 度回転します。

たとえば、マウスがオブジェクトを北に配置する必要がある位置にある場合、つまり回転値 = 0 の場合、オブジェクトは左に 45 度回転するため、270 度回転し、左を指す必要があります。北/上向き。

これは私のコードです:

    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);
    }

編集:追加情報

これらの値は、マウスが画面の右側にあるときに表示されます。オブジェクトは東/右を指す必要がありますが、北/上を指します。

マウス位置 X: 1012

マウス位置 Y: 265

オブジェクト POS X: 400275

オブジェクト位置 Y: 24025

回転: 0

編集 2: _rotation の使用方法

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();
    }

編集 3: 作業の修正

    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;
    }
4

1 に答える 1

2

次のドキュメントを参照してくださいMath.Atan2

戻り値は、x 軸と、原点 (0,0) から始まり点 (x,y) で終わるベクトルによって形成されるデカルト平面の角度です。

したがってAtan2(0,1)、pi/2、または真上 (北) になります。

つまり、測定は 0 から始まり、真東 (右) で反時計回りに回転します。0度を期待しているようです。まっすぐに時計回りに回転する必要があるため、それを反映するようにロジックを調整する必要があります。

于 2012-07-09T18:07:07.580 に答える