How to rotate a vertex around a certain point?

前端 未结 6 1389
南旧
南旧 2020-11-29 04:09

Imagine you have two points in 2d space and you need to rotate one of these points by X degrees with the other point acting as a center.

float distX = Math.a         


        
6条回答
  •  天涯浪人
    2020-11-29 04:35

    Here a version that cares the rotate direction. Right (clockwise) is negative and left (counter clockwise) is positive. You can send a point or a 2d vector and set its primitives in this method (last line) to avoid memory allocation for performance. You may need to replace vector2 and mathutils to libraries you use or to java's built-in point class and you can use math.toradians() instead of mathutils.

    /**
     * rotates the point around a center and returns the new point
     * @param cx x coordinate of the center
     * @param cy y coordinate of the center
     * @param angle in degrees (sign determines the direction + is counter-clockwise - is clockwise)
     * @param px x coordinate of point to rotate 
     * @param py y coordinate of point to rotate 
     * */
    
    public static Vector2 rotate_point(float cx,float cy,float angle,float px,float py){
        float absangl=Math.abs(angle);
        float s = MathUtils.sin(absangl * MathUtils.degreesToRadians);
        float c = MathUtils.cos(absangl * MathUtils.degreesToRadians);
    
        // translate point back to origin:
        px -= cx;
        py -= cy;
    
        // rotate point
        float xnew;
        float ynew;
        if (angle > 0) {
            xnew = px * c - py * s;
            ynew = px * s + py * c;
        }
        else {
            xnew = px * c + py * s;
            ynew = -px * s + py * c;
        }
    
        // translate point back:
        px = xnew + cx;
        py = ynew + cy;
        return new Vector2(px, py);
    }
    

    Note that this way has more performance than the way you tried in your post. Because you use sqrt that is very costly and in this way converting from degrees to radians managed with a lookup table, if you wonder. And so it has very high performance.

提交回复
热议问题