问题描述
我有一个矩形,并且有一些直线从矩形的中心向外延伸到矩形外部的任意位置。我需要将它们夹在矩形边缘上,所以端点将位于矩形上。我尝试使用交集算法,它可以工作,但是它很慢,因为它可以处理任何类型的碰撞,而我有特定的条件:线段的起点始终在矩形的中心,线的终点始终在矩形的外部,也许有一些快速算法呢?
解决方法
我假设矩形尺寸为width,height
,矩形中心位于(0,0)
(否则,从endx,endy
变量中减去中心坐标,并将其添加到最终结果中)
if abs(endx) * height <= abs(endy) * width //top or bottom side
return height/2 * endx / abs(endy),sign(endy) * height/2
else //left or right side
return sign(endx) * width/2,width/2 * endy / abs(endx)
Python快速检查:
from math import copysign
def rectclamp(rectcenterx,rectcentery,width,height,lineendx,lineendy):
endx = lineendx - rectcenterx
endy = lineendy - rectcentery
if abs(endx) * height <= abs(endy) * width: #at top or bottom
return (rectcenterx + height / 2 * endx / abs(endy),rectcentery + copysign(1,endy) * height / 2)
else:
return (rectcenterx + copysign(1,endx) * width/2,rectcentery+ width/2 * endy / abs(endx))
print(rectclamp(6,4,12,8,9,9))
print(rectclamp(6,27,10))
print(rectclamp(6,-12,-8))
>>>
(8.4,8.0) #top edge
(12.0,5.714285714285714) # right edge
(0.0,0.0) #corner