summaryrefslogtreecommitdiff
path: root/objects/Body.lua
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-02-20 16:39:45 +0800
committerEltrac <hi@guhub.cn>2025-02-20 16:39:45 +0800
commit6fac71363024403c8bc5e92d286153dbe48b389a (patch)
treea469c152cdfbb882b323dacd1447c7bcd0bc0124 /objects/Body.lua
parent13a208ec28b21279a20438800f5b0acac43eaf1b (diff)
refactor: use Body object
- Body defines an object's size and shape - Body provides a universal function to detect collision
Diffstat (limited to 'objects/Body.lua')
-rw-r--r--objects/Body.lua49
1 files changed, 49 insertions, 0 deletions
diff --git a/objects/Body.lua b/objects/Body.lua
new file mode 100644
index 0000000..72dbbe5
--- /dev/null
+++ b/objects/Body.lua
@@ -0,0 +1,49 @@
+Body = {}
+Body.__index = Body
+
+function Body:new(shape, sizeA, sizeB, sizeC)
+ local obj = {
+ shape = shape,
+ r = (shape == "circle" and sizeA or nil),
+ w = (shape == "rectangle" and sizeA or nil),
+ h = (shape == "rectangle" and sizeB or nil)
+ }
+
+ setmetatable(obj, Body)
+
+ return obj
+end
+
+function Body:collide(other, x1, y1, x2, y2)
+ if self.shape == "circle" and other.shape == "circle" then
+ -- circle to circle
+ local dx = x2 - x1
+ local dy = y2 - y1
+ local distance = math.sqrt(dx * dx + dy * dy)
+ return distance < (self.r + other.r)
+ elseif self.shape == "rectangle" and other.shape == "rectangle" then
+ -- rect to rect
+ return x1 < x2 + other.w and x1 + self.w > x2 and y1 < y2 + other.h and y1 + self.h > y2
+ elseif self.shape == "circle" and other.shape == "rectangle" then
+ -- circle to rect
+ local closestX = math.max(x2, math.min(x1, x2 + other.w))
+ local closestY = math.max(y2, math.min(y1, y2 + other.h))
+ local dx = x1 - closestX
+ local dy = y1 - closestY
+ return (dx * dx + dy * dy) < (self.r * self.r)
+ elseif self.shape == "rectangle" and other.shape == "circle" then
+ return other:collide(self, x2, y2, x1, y1)
+ end
+
+ return false
+end
+
+function Body:draw(x, y)
+ if self.shape == "circle" then
+ -- 绘制圆形
+ love.graphics.circle("fill", x, y, self.r)
+ elseif self.shape == "rectangle" then
+ -- 绘制矩形
+ love.graphics.rectangle("fill", x - self.w / 2, y - self.h / 2, self.w, self.h)
+ end
+end