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

こ雲淡風輕ζ 提交于 2019-12-02 02:49:43

问题


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

I don't know trig and need some help.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3369236/how-to-make-a-sprite-point-at-the-mouse-xna-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!