跳转至内容

06. 小球,碰撞,源码学习

3.2,主要看了 Balatro 的源码,用 AI 加了中文注释,一点点看吧,不动脑子这一块。

Ball

创建了一个最简单的 Ball 类,然后在 PlayState 中实例化了一个小球。

lua
Ball = Class {}

function Ball:init(skin)
    self.width = 8
    self.height = 8
    self.dy = 0
    self.dx = 0
    self.skin = skin
end

function Ball:update(dt)
    self.x = self.x + self.dx * dt
    self.y = self.y + self.dy * dt

    if self.x <= 0 then
        self.x = 0
        self.dx = -self.dx
        gSounds['wall-hit']:play()
    end

    if self.x >= VIRTUAL_WIDTH - self.width then
        self.x = VIRTUAL_WIDTH - self.width
        self.dx = -self.dx
        gSounds['wall-hit']:play()
    end

    if self.y <= 0 then
        self.y = 0
        self.dy = -self.dy
        gSounds['wall-hit']:play()
    end
end

function Ball:render()
    love.graphics.draw(
        gTextures['main'],
        gFrames['balls'][self.skin],
        self.x, self.y
    )
end

function Ball:reset()
    self.x = (VIRTUAL_WIDTH - self.width) / 2
    self.y = (VIRTUAL_HEIGHT - self.height) / 2
    self.dx = 0
    self.dy = 0
end

function Ball:collides(target)
    if self.x > target.x + target.width or target.x > self.x + self.width then
        return false
    end

    if self.y > target.y + target.height or target.y > self.y + self.height then
        return false
    end

    return true
end