这是我为LOVE2D引擎在Lua中制作的一个小库,它使用分离轴定理来解决碰撞问题。
当我让我的SAT程序工作起来,并开始使用各种多边形进行测试时,我感到非常开心。它在大多数情况下都可以正常工作,并且为它们提供了正确的最小平移向量。奇怪的是-如果两个形状都有锐角,那么这些角会导致程序失败,返回碰撞,即使形状没有接触,或者更不寻常的是,它会给出令人费解的最小平移向量。我已经检查了返回法线的函数-因为我觉得这是可能出错的第一点,但它似乎运行良好。
这是处理我的碰撞的主要功能。
function findIntersection(shape1, shape2)
--Get axes to test.
--MTV means 'minimum translation vector' ie. the shortest vector of intersection
local axes1 = {}
local axes2 = {}
local overlap = false
local MTV = {direction = 0, magnitude = 99999}
for i, vert in pairs(shape1.hitbox) do
nrm = getNormal(shape1.hitbox, i)
table.insert(axes1, nrm)
end
for i, vert in pairs(shape2.hitbox)do
nrm = getNormal(shape2.hitbox, i)
table.insert(axes2, nrm)
end
--print(#axes1 .. ' ' .. #axes2)
--now that we have the axes, we have to project along each of them
for i, axis in pairs(axes1) do
test1 = hitboxProj(shape1, vectorToCoord(axis.direction, axis.magnitude))
test2 = hitboxProj(shape2, vectorToCoord(axis.direction, axis.magnitude))
if test2.max > test1.min or test1.max > test2.min then
if test2.max - test1.min < MTV.magnitude then
MTV.direction = axes1[i].direction
MTV.magnitude = test2.max - test1.min
end
else
return false
end
end
--now that we have the axes, we have to project along each of them
for i, axis in pairs(axes2) do
test1 = hitboxProj(shape1, vectorToCoord(axis.direction, axis.magnitude))
test2 = hitboxProj(shape2, vectorToCoord(axis.direction, axis.magnitude))
if test2.max > test1.min or test1.max > test2.min then
if test2.max - test1.min < MTV.magnitude then
MTV.direction = axes2[i].direction
MTV.magnitude = test2.max - test1.min
end
else
return false
end
end
return {MTV}
end
我的项目文件在Github上,链接为https://github.com/ToffeeGoat/ToffeeCollision
math.atan(y/x)
替换为math.atan2( y, x )
。 - DavisDude