如何测试圆是否在旋转的对象中

时间:2011-06-13 00:11:11

标签: javascript svg collision-detection raphael

我正在使用Raphaeljs创建用于创建图表的Web应用程序。其中一种形状是钻石,它只是一个旋转45度的矩形。我需要测试一个圆是否属于旋转的图像,我不知道该如何去做。

1 个答案:

答案 0 :(得分:2)

如果你有钻石:

var diamond = paper.rect(rect_x, rect_y, size, size);
diamond.rotate(45);

然后水平线上的两个角有坐标(nx1,ny)和(nx2,ny),其中

ny  = rect_y + rect_w/2;
nx1 = rect_x + rect_w*(1-Math.sqrt(2))/2;
nx2 = rect_x + rect_w*(1+Math.sqrt(2))/2;

然后你在这个钻石内部创建一个钻石,该钻石的圆半径小。

var circle = paper.circle(cx, cy, r);
nx1 += r*Math.sqrt(2);
nx2 -= r*Math.sqrt(2);

Diagram showing circle in diamond

然后你测试圆的中心是否在这颗钻石的四边之间:

if (cy < ny - nx1 + cx &&
    cy > ny - nx2 + cx &&
    cy > ny + nx1 - cx &&
    cy < ny + nx2 - cx)
  {Circle is inside the diamond}