--线与线的碰撞
function LineToLine(linePointStart1,linePointEnd1,linePointStart2,linePointEnd2)
--这里涉及到一个叉乘的概念,叉乘的模的公式为 vec1length * vec2length * sin角度 (这里可以看出当模为0的时候两条直线平行)
--向量表示为X12*Y34 - X34*Y12 及为模
local lineVec1 = {x = linePointEnd1.x - linePointStart1.x , y = linePointEnd1.y - linePointStart1.y}
local lineVec2 = {x = linePointEnd2.x - linePointStart2.x , y = linePointEnd2.y - linePointStart2.y}
--lineVec1 叉乘 lineVec2
local mo = math.abs(lineVec1.x * lineVec2.y - lineVec1.y * lineVec2.x)
if (mo == 0) then
--判断点跟直线是否同个线段中
if PointToLine(linePointStart1,linePointStart2,linePointEnd2) then
return true
elseif PointToLine(linePointEnd1,linePointStart2,linePointEnd2) then
return true
elseif PointToLine(linePointStart2,linePointStart1,linePointEnd1) then
return true
end
return false
end
local lineVec3 = {x = linePointStart2.x - linePointStart1.x , y = linePointStart2.y - linePointStart1.y}
local lineVec4 = {x = linePointEnd2.x - linePointStart1.x , y = linePointEnd2.y - linePointStart1.y}
local lineVec5 = {x = linePointStart1.x - linePointStart2.x , y = linePointStart1.y - linePointStart2.y}
local lineVec6 = {x = linePointEnd1.x - linePointStart2.x , y = linePointEnd1.y - linePointStart2.y}
--这里叉乘一下判断一个两个点是否在lineVec1的两边
local sin1 = lineVec3.x * lineVec1.y - lineVec1.x * lineVec3.y
local sin2 = lineVec1.x * lineVec4.y - lineVec1.y * lineVec4.x
--这里叉乘一下判断两个点是否在lineVec2的连边
local sin3 = lineVec5.x * lineVec2.y - lineVec2.x * lineVec5.y
local sin4 = lineVec2.x * lineVec6.y - lineVec6.x * lineVec2.y
if sin1 > 0 and sin2 > 0 and sin3 > 0 and sin4 > 0 then
return true
end
return false
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