Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...