Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c# - Rotation of an object around a central vector2 point

I should preface this with I am not anywhere near a math person. The code I've found in another question seems to be working somewhat... except that it causes the object I place to rotate in a large circle mostly off screen.

Here's the code:

public void Update(GameTime gameTime)
{
    Location = RotateAboutOrigin(Center, Origin, 0.01f);
}

public Vector2 RotateAboutOrigin(Vector2 point, Vector2 origin, float rotation)
{
    var u = point - origin; //point relative to origin  

    if (u == Vector2.Zero)
         return point;

    var a = (float)Math.Atan2(u.Y, u.X); //angle relative to origin  
    a += rotation; //rotate  

    //u is now the new point relative to origin  
    u = u.Length() * new Vector2((float)Math.Cos(a), (float)Math.Sin(a));
    return u + origin;
} 

Location is set by a mouse click in an arbitrary position around the central vector.

Center is the (you guessed it) center of the object I 'place' when I click. It's determined by simply dividing the height and width of the texture.

Origin is the vector2 I am attempting to rotate around. It's statically set at 384,384.


As best I can tell, it's getting the distance between the two vectors and then using atan2 to determine the angle. The rest afterward is a mystery to me. I'm aware that I should learn what everything does, and I do intend to when I go to college(only a decade late) starting in the spring. I've tried reading up on them, but I'm lost. Any help would be appreciated.

Also, if you have a good trig for dummies site you can recommend, I would be delighted to read through it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an alternative:

public Vector2 RotateAboutOrigin(Vector2 point, Vector2 origin, float rotation)
{
    return Vector2.Transform(point - origin, Matrix.CreateRotationZ(rotation)) + origin;
} 

It does the "translate to the world origin, rotate, then translate back" bit.

This rotates 'point' around 'origin' by 'rotation' radians regardless of where origin is relative to the world origin. The trig happens in the 'CreateRotationZ()' built in function. To see how it applies the trig, reflect that method in the framework.

Edit: fixing variable name


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...