13. 翻译,搬运,碰撞检测
3.9,用 AI 翻译了 BYTEPATH 教程全文,又搬运了一个 breakout 的新教程。
Paddle Collision
计算球的 x 和挡板中心的距离,越靠近左边 → 往左弹,越靠近右边 → 往右弹。
速度 dx 根据差值大小来调整。
lua
if self.ball.x < self.paddle.x + (self.paddle.width / 2) and self.paddle.dx < 0 then
self.ball.dx = -50 + -(8 * (self.paddle.x + self.paddle.width / 2 - self.ball.x))
elseif self.ball.x > self.paddle.x + (self.paddle.width / 2) and self.paddle.dx > 0 then
self.ball.dx = 50 + (8 * math.abs(self.paddle.x + self.paddle.width / 2 - self.ball.x))
endBrick Collision
判断碰撞来自哪个方向,然后反转。
lua
for k, brick in pairs(self.bricks) do
if brick.inPlay and self.ball:collides(brick) then
brick:hit()
if self.ball.x + 2 < brick.x and self.ball.dx > 0 then
self.ball.dx = -self.ball.dx
self.ball.x = brick.x - 8
elseif self.ball.x + 6 > brick.x + brick.width and self.ball.dx < 0 then
self.ball.dx = -self.ball.dx
self.ball.x = brick.x + 32
elseif self.ball.y < brick.y then
self.ball.dy = -self.ball.dy
self.ball.y = brick.y - 8
else
self.ball.dy = -self.ball.dy
self.ball.y = brick.y + 16
end
self.ball.dy = self.ball.dy * 1.02
break
end
end