旋转矩形上的点

时间:2011-07-29 00:49:31

标签: flash actionscript-3 algorithm geometry

我试图计算一个矩形的左下角,因为它在周围旋转。我试图谷歌它,但显然我错过了一些东西。我正在尝试使用变换矩阵来计算点。

对于我的设置,我有一个名为“test”的矩形剪辑和一个名为“pnt”的剪辑,我试图保持在左下角。这是我演示的代码。我刚把它扔到时间轴的第一帧进行测试:

//declare initial position of points
pnt.x = (test.x - test.width/2);
pnt.y = (test.y + test.height/2);

//distance between corner and center
var dx:Number = pnt.x - test.x;
var dy:Number = pnt.y - test.y;

addEventListener(Event.ENTER_FRAME,rotate);


//x' = xc + dx cos(theta) - dy sin(theta)
//y' = yc + dx sin(theta) + dy cos(theta)
function rotate(e:Event):void{
    test.rotation++;

    // use the transformation matrix to calculate the new x and y of the corner
    pnt.x = test.x + dx*Math.cos(test.rotation*(Math.PI/180)) - dy*Math.sin(test.rotation*(Math.PI/180));
    pnt.y = test.y + dx*Math.sin(test.rotation*(Math.PI/180)) + dy*Math.cos(test.rotation*(Math.PI/180));

    trace("X: " + Math.cos(rotation));
    trace("Y: " + pnt.y);
    // calculate the new distance to the center
    dx = pnt.x - test.x;
    dy = pnt.y - test.y;
}

2 个答案:

答案 0 :(得分:6)

我们可以通过

模拟单点的轨迹
(x',y') = (xc + r cos(theta + theta0), yc + r sin(theta + theta0))

,其中

(x', y') = new position
(xc, yc) = center point things rotate around
(x, y) = initial point
r = distance between (x,y) and (xc, yc)
theta = counterclockwise rotation, in radians
theta0 = initial rotation of (x,y), in radians

我们的初步观点告诉我们

r sin(theta0) = (y - yc) 
r cos(theta0) = (x - xc)

借助三角形的力量:

r cos(theta + theta0) =
r cos(theta)cos(theta0) - r sin(theta)sin(theta0) = 
cos(theta)(x - xc) - sin(theta)(y - yc)

r sin(theta + theta0) = 
r sin(theta)cos(theta0) + r cos(theta)sint(theta0)
sin(theta)(x - xc) + cos(theta)(y - yc)

因此,给定

  1. 东西围绕
  2. 旋转的中心点(xc, yc)
  3. 跟踪(x, y)的点 - (您的矩形角)
  4. 以弧度为单位的轮换theta
  5. 该点的新位置将是:

    x' = xc + dx cos(theta) - dy sin(theta)
    y' = yc + dx sin(theta) + dy cos(theta)
    

    dxdy提供

    dx = x - xc
    dy = y - yc    
    

答案 1 :(得分:0)

对于那些通过谷歌发现这一点的人......

以上是JavaScript / jQuery表单中的上述答案,其中$element$('#element') jQuery对象,iDegrees是您希望旋转的角度,iX / { {1}}是您希望了解其目的地的点的坐标,iY / iCenterXPercent表示元素中的百分比(根据CSS的iCenterYPercent),其中轮换将是发生:

transform-origin

例如:

function XYRotatesTo($element, iDegrees, iX, iY, iCenterXPercent, iCenterYPercent) { var oPos = $element.position(), iCenterX = ($element.outerWidth() * iCenterXPercent / 100), iCenterY = ($element.outerHeight() * iCenterYPercent / 100), iRadians = (iDegrees * Math.PI / 180), iDX = (oPos.left - iCenterX), iDY = (oPos.top - iCenterY) ; return { x: iCenterX + (iDX * Math.cos(iRadians)) - (iDY * Math.sin(iRadians)), y: iCenterY + (iDX * Math.sin(iRadians)) + (iDY * Math.cos(iRadians)) }; }; 的左上角在左下角旋转45度后会在哪里结束?

<div id='element'>...</div>