在2D游戏开发中,碰撞检测是一个非常常见且重要的算法。碰撞检测用于确定游戏对象是否相互接触或重叠,从而触发相应的游戏逻辑,如物理反应、得分计算等。
以下是用 Lua 实现的简单的轴对齐边界框(AABB)碰撞检测算法:
-- 定义矩形结构
Rectangle = {}
Rectangle.__index = Rectangle
function Rectangle:new(x, y, width, height)
local rect = {
x = x,
y = y,
width = width,
height = height
}
setmetatable(rect, Rectangle)
return rect
end
-- AABB碰撞检测函数
function checkCollision(rect1, rect2)
return rect1.x < rect2.x + rect2.width and
rect1.x + rect1.width > rect2.x and
rect1.y < rect2.y + rect2.height and
rect1.y + rect1.height > rect2.y
end
-- 测试AABB碰撞检测
local rect1 = Rectangle:new(0, 0, 50, 50)
local rect2 = Rectangle:new(25, 25, 50, 50)
local rect3 = Rectangle:new(100, 100, 50, 50)
if checkCollision(rect1, rect2) then
print("rect1 和 rect2 发生碰撞")
else
print("rect1 和 rect2 没有发生碰撞")
end
if checkCollision(rect1, rect3) then
print("rect1 和 rect3 发生碰撞")
else
print("rect1 和 rect3 没有发生碰撞")
end
在这个实现中:
Rectangle 结构表示一个矩形,包含其左上角坐标 (x, y) 和尺寸 width 和 height 。
checkCollision 函数接受两个矩形 rect1 和 rect2 ,通过比较它们的边界来确定是否发生碰撞。
- 测试代码创建了三个矩形,并调用
checkCollision 函数来检测它们之间的碰撞情况。
AABB碰撞检测的基本思想是检查两个矩形的边界是否重叠。具体来说,如果一个矩形的右边界在另一个矩形的左边界右侧,且左边界在另一个矩形的右边界左侧,同时上边界在另一个矩形的下边界上方,且下边界在另一个矩形的上边界下方,则这两个矩形发生碰撞。
AABB碰撞检测适用于许多2D游戏场景,如角色与障碍物的碰撞、子弹与敌人的碰撞等。它简单高效,适合实时性要求较高的游戏应用。
当然,碰撞检测还有其他复杂的算法,如圆形碰撞检测、像素级碰撞检测和分离轴定理(SAT)等,可以根据具体需求选择合适的算法。 |