これは、分離軸定理を使用して衝突を解決する Lua の LOVE2D エンジン用に私が作成していた小さなライブラリです。
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