Search code examples
c#visual-studioxna2d-games

Rotating and Positioning XNA


I am making a top down shooter and have designed my game so that the sprite rotates when the mouse moves around him, I have this working but I would like the sprite to point to the mouse from the gun.

If you look at this image:
i
The cross hair is where the mouse is and the sprite is not facing the mouse. Is there a way I can rotate it?

Lastly, the cross hair I have as you can see in the image above is locked onto the Windows mouse cursor, however it follows the mouse pointer from the top left of the cross hair as it is just a texture2d. Is there a way I can make it so the cross hair is set to the middle.


Solution

  • For your first question you can use trigonometry:

    Image showing how to apply trig

    So you should be able to use something like

    Math.ArcTangent(Mouse.Y - Player.Y, Mouse.X - Player.X);
    

    To find the angle the player needs to turn.

    As for centering the cursor, you need to modify the spritebatch.Draw() statement.

    As mentioned here:

    public void Draw (
             Texture2D texture,
             Vector2 position,
             Nullable<Rectangle> sourceRectangle,
             Color color,
             float rotation,
             Vector2 origin,
             Vector2 scale,
             SpriteEffects effects,
             float layerDepth
    )
    

    Origin

    Type: Vector2

    The sprite origin; the default is (0,0) which represents the upper-left corner.

    So if you changed the origin in the draw statement to:

    new Vector2(texture.width / 2, texture.height / 2);
    

    It would draw the cursor centered.