圆形和矩形的碰撞检测

圆形和矩形的碰撞检测,第1张

概述首先来说明一下核心思想 无非是三种状态: 1、圆心在矩形中 2、圆心在矩形外,但在其某一边的侧面 3、圆心在矩形外、不再某一边的侧面 圆心在矩形中的情况十分好处理,这里就不说了。 下面来说一下2、3情况的核心应对思路: 首先,拿到矩形的四个顶点。 算出圆心到四个顶点分别的距离。 给距离从小到大排一下序。 取其中两个最小距离的点,求出圆心到这两点之间直线(或延长线)上最短距离的那个点。 重点来了:


首先来说明一下核心思想


无非是三种状态:

1、圆心在矩形中

2、圆心在矩形外,但在其某一边的侧面

3、圆心在矩形外、不再某一边的侧面


圆心在矩形中的情况十分好处理,这里就不说了。

下面来说一下2、3情况的核心应对思路:


首先,拿到矩形的四个顶点。

算出圆心到四个顶点分别的距离。

给距离从小到大排一下序。

取其中两个最小距离的点,求出圆心到这两点之间直线(或延长线)上最短距离的那个点。

重点来了:

这时候要看这个点是在两点之间,还是在这条直线的延长线上。如果是之间,就是情况2。再延长线上就是3。
分别做处理,如果是情况2就算出两点距离,看看跟半径的关系判断是否碰撞。

如果是3就算出圆心到距离圆心最近的顶点的距离,看看它和半径的关系。


Lua代码如下:

(注:这个是本人洗澡的时候灵感突现想出的IDea,半夜写的算法。没有单独摘出来方法,将会在以后改进。请关注本人博客或Github: https://github.com/Schrodinger123)


--圆心,半径	local circle = {		x = 0,y = 0,r = 5	}	-- 矩形位置,宽高	local Box = {		x = 5,y = 5,w = 3,h = 3	}	-- 矩形四个点	Box.ld = {		x = Box.x-Box.w/2,y = Box.y-Box.h/2	}	Box.rd = {		x = Box.x+Box.w/2,y = Box.y-Box.h/2	}	Box.lu = {		x = Box.x-Box.w/2,y = Box.y+Box.h/2	}	Box.ru = {		x = Box.x+Box.w/2,y = Box.y+Box.h/2	}	-- 求两点间距离方法	function p2pdis(p1,p2)		return math.abs(math.sqrt(math.pow(p1.x-p2.x,2)+math.pow(p1.y-p2.y,2)))	end	-- 算出每个点距离圆心距离	local line = {		[1] = {dis = p2pdis(circle,Box.ld),point = "ld"},[2] = {dis = p2pdis(circle,Box.rd),point = "rd"},[3] = {dis = p2pdis(circle,Box.lu),point = "lu"},[4] = {dis = p2pdis(circle,Box.ru),point = "ru"},}	-- 从小到大排序	function ts(v1,v2)		return v1.dis < v2.dis	end	table.sort(line,ts)	-- 算出圆心在距离它最近的边(或边延长线)上的最近的点坐标	local pointInline = {}	local status = 0 --0为竖着 1为横着	if Box[line[1].point].y == Box[line[2].point].y then		status = 1	end	pointInline.x = status == 0 and Box[line[1].point].x or circle.x	pointInline.y = status == 0 and circle.y or Box[line[1].point].y	-- 算距离	if (status == 1 and (pointInline.x < Box.ld.x or pointInline.x > Box.rd.x)) or (status == 0 and (pointInline.y < Box.ld.y or pointInline.y > Box.lu.y)) then		--完全在外边		local p2ndis = p2pdis(circle,Box[line[1].point])		print("外距离"..p2ndis)		print(p2ndis > circle.r and "不碰撞" or "碰撞")	else		--圆心在附近		local p2ldis = p2pdis(circle,pointInline)		print("距离"..p2ldis)		print(p2ldis > circle.r and "不碰撞" or "碰撞")	end
总结

以上是内存溢出为你收集整理的圆形和矩形的碰撞检测全部内容,希望文章能够帮你解决圆形和矩形的碰撞检测所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1063842.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-26
下一篇2022-05-26

发表评论

登录后才能评论

评论列表(0条)

    保存