Rotation of an object around a central vector2 point

北城余情 提交于 2019-11-29 07:04:40
Steve H

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

George Duckett

This is easier done using matricies, although the underlying theory is possibly a bit harder to understand, you don't really need to know it all to use it (standing on the shoulders of giants and all that).

To rotate a vector about the origin:

Vector2.Transform(PosComponent.Direction, Matrix.CreateRotationZ(-0.1f))

Where PosComponent.Direction is my vector and -0.1f is the amount it want to rotate by (in radians, not degrees).

Since you want to rotate a vector around something other than the origin you'll need to move the vector first, then rotate, then move it back. That's basically what you're code above is doing, except to get the angle and do the rotation it's using trig.

Do do a rotation:

  1. You get the point relative to the origin (as in your code),
  2. then rotate either
    • using trig to get the angle, manipulate it then recalculate the vector (as in your code),
    • or using matricies (as in my code).
  3. Finally move the vector back (as in your code).

This question and my answer, might be of some use in understanding trig: Get position of point on circumference of circle, given an angle?

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