Note that there are some explanatory texts on larger screens.

plurals
  1. PORotating towards mouse in C# is not working correctly
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>This is my code:</p> <pre><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); } </code></pre> <p><b>EDIT: extra info</b></p> <p>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.</p> <p>MOUSE POS X: 1012</p> <p>MOUSE POS Y: 265</p> <p>OBJECT POS X: 400275</p> <p>OBJECT POS Y: 24025</p> <p>ROTATION: 0</p> <p><b>EDIT 2: how _rotation is used</b></p> <pre><code>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(); } </code></pre> <p><b>EDIT 3: The working fix thingy</b></p> <pre><code> 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; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload