圆与线段碰撞检测

圆与线段的碰撞检测算法利用了一个向量在另一个向量的投影的原理。

假设向量p1p为v1, 向量p1p2为v2,p0为v1在v2上的投影点,则p1p0为v1在v2上的投影。

两个向量点乘v1.dot(v2) = v1.length() * v2.length() * cos(theta) = x1 * x2 + y1 * y2,当v2经过单位化后,点乘的结果就变成的投影向量p1p0的长度,设为u。

当p位于p1左侧时,theta角度大于90度,cos值为负,所以u <= 0;当p位于p2右侧时,u >= v2.length()。

依此可以算出到圆心p到线段上距离最近的点,如果到该点距离小于圆半径r,则圆与线段相交。


圆与线段碰撞检测的算法实现:

#ifndef __CIRCLE_LINESEG_INTERSECTION_H__
#define __CIRCLE_LINESEG_INTERSECTION_H__

#include 
   
   
    
    
#include 
    
    
     
     

// 圆与线段碰撞检测
// 圆心p(x, y), 半径r, 线段两端点p1(x1, y1)和p2(x2, y2)
bool IsCircleIntersectLineSeg(float x, float y, float r, float x1, float y1, float x2, float y2)
{
	float vx1 = x - x1;
	float vy1 = y - y1;
	float vx2 = x2 - x1;
	float vy2 = y2 - y1;

	assert(fabs(vx2) > 0.00001f || fabs(vy2) > 0.00001f);

	// len = v2.length()
	float len = sqrt(vx2 * vx2 + vy2 * vy2);

	// v2.normalize()
	vx2 /= len;
	vy2 /= len;

	// u = v1.dot(v2)
	// u is the vector projection length of vector v1 onto vector v2.
	float u = vx1 * vx2 + vy1 * vy2;

	// determine the nearest point on the lineseg
	float x0 = 0.f;
	float y0 = 0.f;
	if (u <= 0)
	{
		// p is on the left of p1, so p1 is the nearest point on lineseg
		x0 = x1;
		y0 = y1;
	}
	else if (u >= len)
	{
		// p is on the right of p2, so p2 is the nearest point on lineseg
		x0 = x2;
		y0 = y2;
	}
	else
	{
		// p0 = p1 + v2 * u
		// note that v2 is already normalized.
		x0 = x1 + vx2 * u;
		y0 = y1 + vy2 * u;
	}

	return (x - x0) * (x - x0) + (y - y0) * (y - y0) <= r * r;
}

#endif // __CIRCLE_LINESEG_INTERSECTION_H__

    
    
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值