开发者

Function to rotate a point around another point

开发者 https://www.devze.com 2023-04-05 19:46 出处:网络
so I\'ve got a math function here that supposed to return a rotated point, and takes an original point, point to rotate around (origin) and radians to rotate it.

so I've got a math function here that supposed to return a rotated point, and takes an original point, point to rotate around (origin) and radians to rotate it.

However it rotating only at half开发者_运维知识库 speed (aka 180 degree movement = 90 degree rotation)

sf::Vector2f RotatePoint(sf::Vector2f origin, sf::Vector2f point, float radian) {   
    float s = sin(radian);   
    float c = cos(radian);  

    // translate point back to origin:  
    point.x -= origin.x;   
    point.y -= origin.y;   

    // rotate point   
    float xnew = point.x * c - point.y * s;   
    float ynew = point.x * s + point.y * c; 

    // translate point back to global coords:
    sf::Vector2f TranslatedPoint;
    TranslatedPoint.x = xnew + origin.x;  
    TranslatedPoint.y = ynew + origin.y; 

    return TranslatedPoint;
} 


The function looks ok to me. The rotation, in case you're wondering, is just multiplying a vector by the 2D Euclidean rotation matrix (http://en.wikipedia.org/wiki/Rotation_matrix ). The only errors I can think of are some misunderstanding of the usage of the function. E.g. that 2*PI radians = 360 degrees, or that the rotation is counterclockwise.


Your code seems fine. Do we agree that 180° in degrees is Pi in radians ?


The function is fine. However, you might want to fresh up on your linear algebra a bit: You basically compute

return rotation * (point - origin) + origin;

with rotation as the matrix consisting of cos(radian) on the diagonals and +/- sin(radian) on the off-diagonals. So, the whole function is a one-liner if you let your linear algebra library compute that matrix; and if you factor out the -origin part (remember, linear algebra is linear), it becomes:

return rotation * point + ( - rotation * origin + origin );

where the second part is point-invariant and can be precomputed.

0

精彩评论

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