4
votes

i've been trying to get a sprite to face my cursor using XNA, it works almost perfectly, but instead of the centre of the face of the sprite, it's the corner that points to the cursor... which is no good for a game where something in the centre of the sprite must face the cursor, just wondering if there's a way to make it point from a certain point... that sounds confusing but i hope somebody gets it :)

heres the code im using:

to get the angle:

direction = mousePos - position;
rotation = (float)Math.Atan2(direction.Y, direction.X);

to Draw the sprite:

spriteBatch.Begin();
spriteBatch.Draw(sprite, position, null, Color.White, rotation + 90, origin, 1.0f, SpriteEffects.None, 0);
spriteBatch.End();

so if this is my sprite: [ ] the top left corner will point to the cursor, not the middle :P

5
Try using rotation + 45 or rotation - 45thedaian
Are you setting your origin to the center of the sprite correctly?Andrew Russell

5 Answers

4
votes

dont add 90. whatever you do. the Atan2 function will be returning the angle in Radians (much nicer than degrees once you start using them). so adding 90 is going to throw it right off.

if you want to alter the rotation of the image by 90 degrees, then you need to add half the value of PI (360 degree = 2xPI).

so this should take care of it.

spriteBatch.Draw(sprite, position, null, Color.White, rotation + (Math.PI*0.5f), origin, 1.0f, SpriteEffects.None, 0);
1
votes

I'm not sure if the adding 90 hurts the end result or not like the person above me said, but the reason why the sprites corner is facing ur mouse is because in XNA it uses the top left most point of the sprite as the origin. set it to the center of the sprite and problem solved.

Look something like this:

spriteBatch.Draw(sprite, position, null, Color.White, rotation + 90,new Vector2(sprite.Width /2, sprite.Height /2) , 1.0f, SpriteEffects.None, 0);

this will set it to the relative middle of the sprite texture.

0
votes
direction.x = mousePos.x - (position.x + spriteWidth / 2);
direction.y = mousePos.y - (position.y + spriteHeight / 2);

It looks ugly but avoid creating a new vector2 will contribute saving some fps :)

0
votes

If you still want a answer after 7 years xD You need to set the WindowHandle.

Mouse should default to reporting its position relative to the game window, but can be configured by assigning the appropriate window handle to Mouse.WindowHandle.

The documentation is here. I think this is also a Answer.

0
votes

Hi in xna they don't have degrees they have something else that i dont know the name of and this means that pi i 180 degrees and to get 90 degrees you simply take 3,14 / 2 = 1,57

so: rotation + 1.57