检测点是否在两条平行线段之间_如何检测两个线段相交的位置?

FWIW,以下功能(在C中)都检测线交叉并确定交点。它基于Andre LeMothe的“ Windows游戏编程大师的诀窍 ”中的算法。它与其他答案中的某些算法(例如Gareth's)没有什么不同。LeMothe然后使用Cramer的规则(不要问我)自己解决方程。

我可以证明它在我的微弱小行星克隆中起作用,并且似乎正确处理Elemental,Dan和Wodzu在其他答案中描述的边缘情况。它也可能比KingNestor发布的代码更快,因为它是所有的乘法和除法,没有平方根!

我想在那里有一些除以零的可能性,尽管在我的情况下这不是一个问题。很容易修改,以避免崩溃。// Returns 1 if the lines intersect, otherwise 0. In addition, if the lines

// intersect the intersection point may be stored in the floats i_x and i_y.char

get_line_intersection(float p0_x, float p0_y, float p1_x, float p1_y,

float p2_x, float p2_y, float p3_x, float p3_y, float *i_x, float *i_y){

float s1_x, s1_y, s2_x, s2_y;

s1_x = p1_x - p0_x;     s1_y = p1_y - p0_y;

s2_x = p3_x - p2_x;     s2_y = p3_y - p2_y;

float s, t;

s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);

t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

if (s >= 0 && s <= 1 && t >= 0 && t <= 1)

{

// Collision detected

if (i_x != NULL)

*i_x = p0_x + (t * s1_x);

if (i_y != NULL)

*i_y = p0_y + (t * s1_y);

return 1;

}

return 0; // No collision}

顺便说一句,我必须说,在LeMothe的书中,虽然他显然得到了正确的算法,但是他展示的具体例子插错了数字并且计算错误。例如:(4 *(4 - 1)+ 12 *(7 - 1))/(17 * 4 + 12 * 10)

= 844 / 0.88

= 0.44

那让我困惑了几个小时。:(

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值