I am trying to make a simple game in XNA.
I have a player which has spritesheet next to it.
The spritesheet is a sort of weapon, with a tip.
How can I get this sprite to rotate with the tip facing the mouse position?
float y2 = m_Mouse.Y;
float y1 = m_WeaponOrigin.Y;
float x2 = m_Mouse.X;
float x1 = m_WeaponOrigin.X;
// Get angle from mouse position.
m_Radians = (float) Math.Atan2((y2 - y1), (x2 - x1));
Drawing with:
activeSpriteBatch.Draw(m_WeaponImage, m_WeaponPos, r, Color.White, m_Radians, m_WeaponOrigin, 1.0f, SpriteEffects.None, 0.100f);
while this makes it rotate, it does not follow the mouse correctly, and it behaves weirdly.
Any hints on how to make this work?
Another issue I have is to define a point and which is the muzzle, and update it based on the angle as well, so that shots will fire correctly from that point towards the mouse.
Thanks
Screenshots:



Thanks again, turned out to be a fun game.
Basically, use
Math.Atan2.Proof of concept (I used the plus texture for the cursor – it doesn’t show on the sceenshot unfortunately):
“What is
_arrow?”In that example
_arrowis of typeSprite, which might come in handy in some situations, and will sure make your code look a bit cleaner:Declare:
Initiate:
Draw: