--线与圆的碰撞
function LineToCircle(linePoint1,linePoint2,circlePos,radius)
--这里需要分成两种情况,一种是线段两边的点是否在圆内
--如果点到半径的距离
if PointToCircle(linePoint1,circlePos,radius) then
return true
end
if PointToCircle(linePoint2,circlePos,radius) then
return true
end
--寻找圆心最近的点
local lineVec = {x= (linePoint2.x - linePoint1.x) , y = (linePoint2.y - linePoint1.y)}
local pointToLinePoint1 = {x= (circlePos.x - linePoint1.x) , y = (circlePos.y - linePoint1.y)}
local lineLength = math.sqrt(lineVec.x * lineVec.x + lineVec.y * lineVec.y)
--点乘向量公式 相当于 lineLength * pointLinePoint1Length * cos角度
local dot = lineVec.x * pointToLinePoint1.x + lineVec.y * pointToLinePoint1.y
--这里就是pointLinePoint1Length * cos角度 及为lineVec 的投影长度,温馨提示pointLinePoint1ToLine可能为正负值 取决于向量的夹角的cos值
--相当于到线段的投影比例
local pointLinePoint1ToLine = dot / lineLength
local closestX = linePoint1.x + pointLinePoint1ToLine * (linePoint2.x - linePoint1.x)
local closestY = linePoint1.y + pointLinePoint1ToLine * (linePoint2.y - linePoint1.y)
local isInLine = PointToLine({ x = closestX,y = closestY} , linePoint1, linePoint2)
--如果点不在线上面(就是相当于他是在延长线 ) 直接returnfalse
if not isInLine then
return false;
end
--点跟圆的碰撞
local result = PointToCircle({ x = closestX,y = closestY},circlePos,radius)
return result
end
--点与直线的碰撞
function PointToLine(point , linePoint1, linePoint2)
--思想点与线两边线段的距离跟线的距离的判断,相等就是在同一直线
local line1 = math.sqrt((linePoint1.x - point.x) * (linePoint1.x - point.x) + (linePoint1.y - point.y)* (linePoint1.y - point.y))
local line2 = math.sqrt((linePoint2.x - point.x) * (linePoint2.x - point.x) + (linePoint2.y - point.y)* (linePoint2.y - point.y))
local line = math.sqrt((linePoint2.x - linePoint1.x) * (linePoint2.x - linePoint1.x) + (linePoint2.y - linePoint1.y)* (linePoint2.y - linePoint1.y))
return (line1 + line2) == line
end
--点跟圆是否碰撞
function PointToCircle (point,circlePos,radius)
local sqr2 = (point.x - circlePos.x) * (point.x - circlePos.x) + (point.y - circlePos.y) * (point.y - circlePos.y)
return radius * radius >= sqr2
end