开发者

How to make a sprite point at the mouse. XNA C#

If you would look at this diagram link text, I need to find angle A by only knowing the length of all sides of 开发者_Python百科a right triangle.

I don't know trig and need some help.


There are actually 2 questions in your post.

How to make a sprite point at the mouse. XNA C#:

You will have to calculate the direction between the position of the sprite and the position of the mouse. This can be done using trigonometry functions. In this case: Arctangens2

So let's use the math library:

MouseState mouseState = Mouse.GetState();
Math.Atan2((double)mouseState.Y - sprite.Y, (double)mouseState.X - sprite.X); //this will return the angle(in radians) from sprite to mouse.

In your trigonometry example you will see that those values actually are:

Math.Atan2(BC, AC);

or

Math.Atan2(Ydiff, Xdiff);

I hope this helps =D

Cheers,

TomHashNL


I found my final solution to be:

Vector2 direction = targetPosition - currentPosition;
direction.Normalize();
float rotationInRadians = (float)Math.Atan2((double)direction.Y, 
                             (double)direction.X) + MathHelper.PiOver2;

rotationInRadians is a raw value that can be passed to the sprite batch for the correct rotation amount--no further code is needed. Also, you may notice incorrect results if you're rotating the sprite on a corner rather than the middle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜