关于需要反弹功能的2d射击游戏向量计算

velocity速度*-1

function Fruit:update(dt)
    local oldX = self.position.x
    local oldY = self.position.y
    -- 计算新位置
    local newX = oldX + self.velocity.x * dt
    local newY = oldY + self.velocity.y * dt
    -- 更新位置
    self.position.x = newX
    self.position.y = newY
    -- 检查并处理边界碰撞
    self:checkWallCollision()
end

function Fruit:checkWallCollision()
    local screenWidth = love.graphics.getWidth()
    local screenHeight = love.graphics.getHeight()
    
    -- 上下左右边界检测
    if self.position.x < 0 then 
        self.position.x = 0
        self.velocity.x = -self.velocity.x
    end
    if self.position.x + self.width > screenWidth then
        self.position.x = screenWidth - self.width
        self.velocity.x = -self.velocity.x
    end
    if self.position.y < 0 then
        self.position.y = 0
        self.velocity.y = -self.velocity.y
    end
    if self.position.y + self.height > screenHeight then
        self.position.y = screenHeight - self.height
        self.velocity.y = -self.velocity.y
    end
end

 

posted on 2026-02-06 09:50  小沙盒工作室  阅读(0)  评论(0)    收藏  举报