How to rotate a vertex around a certain point?

前端 未结 6 1385
南旧
南旧 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:36

    Here is a way to rotate any point about any other point in 2D. Note that in 3D this can be used as rotation about z axis, z-coordinate of a point being ingored since it doesn't change. Rotation about x-axis and y-axis in 3D can be also easily implemented.

    The code is in JavaScript. The commented lines at the beginning are a test set for the function. They also serve as an example of usage.

    //A = new Array(0,0)
    //S = new Array(-1,0)
    //fi = 90
    //alert("rotujBod: " + rotatePoint(A, S, fi))
    
    function rotatePoint(A, S, fi) {
    /** IN points A - rotated point, S - centre, fi - angle of rotation (rad)
    *    points in format  [Ax, Ay, Az], angle fi (float)
    *       OUT point B
    */
        r = Math.sqrt((A[0] - S[0])*(A[0] - S[0]) + (A[1] - S[1])*(A[1] - S[1]))
        originOfRotation = new Array(S[0] + r, S[1])
        if (A[1] < S[1]) {
            A2 = new Array(A[0], -1*A[1])
            originalAngle = -1*sizeOfAngle(originOfRotation, S, A2)
        } else {
        originalAngle = sizeOfAngle(originOfRotation, S, A)
        }
        x = S[0] + r*Math.cos(fi + originalAngle)
        y = S[1] + r*Math.sin(fi + originalAngle)
        B = new Array(x, y)
        return(B)
    }
    
    function sizeOfAngle(A, S, B) {
        ux = A[0] - S[0]
        uy = A[1] - S[1]
        vx = B[0] - S[0]
        vy = B[1] - S[1]
        if((Math.sqrt(ux*ux + uy*uy)*Math.sqrt(vx*vx + vy*vy)) == 0) {return 0}
        return Math.acos((ux*vx + uy*vy)/(Math.sqrt(ux*ux + uy*uy)*Math.sqrt(vx*vx + vy*vy)))
    }
    

提交回复
热议问题