画布 - 如何找到一个点在对角线上方或下方?

时间:2016-06-10 15:02:36

标签: javascript canvas createjs

在2D游戏中,我需要找到一个物体是否在对角线上方或下方。

任何人都知道如何做到这一点?

(我使用createJS框架)

3 个答案:

答案 0 :(得分:1)

使用上坐标构建三角形以创建形状。例如,如果您的行看起来像:

line

如果使用x2和y1:

,则可以创建形状

triangle

现在只需将三角形添加到路径中,然后执行isPointInPath(x, y),如果为真,则执行上述操作,如果为false则为{

>。

如果你需要检查以下反向过程。

result

(哇!那里有很多箭头......但是你会得到这个想法:))

边缘情况(双关语):如果点非常接近其中一个端点 - >只需延伸线,或使多边形延伸(x1,y1)到区域的边缘。

实际上,考虑一下:三角形可能不太合适,而是使用画布的上边缘作为多边形的一段,然后下一段将垂直线向下到对角线的末端,即从对角线的开头到画布的左上侧的最后一段。我只是懒得重做图形,但你明白了......

答案 1 :(得分:1)

好的,请废弃我以前的答案并改用线路交叉点。从点开始直线测试。如果有一个交点,则该点位于下方,如果没有,则该点位于该线的上方或侧面。

为避免侧面情况(无双关语),请使用插值扩展原始线条。

这是一个执行 line intersection 的功能。要对原始线进行线性插值,只需使用一些极值:

var tx1 = x1 + (x2-x1) * -51000;
var ty1 = y1 + (y2-y1) * -51000;

var tx2 = x1 + (x2-x1) * 53200;
var ty2 = y1 + (y2-y1) * 53200;

更新今天早上我有点匆忙,所以这是一个小小的更新。正如blindman67指出的那样,你可以只使用链接交叉函数中的d并检查s / t是否在标准化范围内(或者只使用交叉产品 - 请参阅他的回答这是更合适的。)

答案 2 :(得分:1)

Use the cross product of the point and the line.

You need to move the whole coord system to the start of the line and then get the cross product of the line and the point. If the result is negative then the point is left of the line, if positive then the point is right of the line, if zero then the point is on the line.

// the point
var px = 100;
var py = 100;

// the line
var lx1 = 20;
var ly1 = 20;
var lx2 = 320;
var ly2 = 120;

// move line end and point so that line start is at 0,0
lx2 -= lx1;
ly2 -= ly1;
px -= lx1;
py -= ly1;

// get cross product
var cross = lx2 * py - ly2 * px;
if(cross < 0){ // point is to the left (anticlockwise)
}else if(cross > 0){ // point is to the right (clockwise)
}else{  // cross must be zero then point is on the line    
}