You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用LÖVE引擎开发Pong游戏时遇rectangle参数错误求助

问题解决:LÖVE引擎Pong游戏rectangle参数错误

错误提示ball.lua:20: bad argument #5 to 'rectangle' (number expected, got nil)的核心原因是变量拼写不一致:

在ball:load()方法里,你把高度变量拼写成了hieght:

self.hieght = 20

但在ball:draw()方法中,调用的是正确拼写的self.height:

love.graphics.rectangle("fill", self.x, self.y, self.width, self.height)

由于self.height从未被赋值,它的值为nil,不符合love.graphics.rectangle对第5个参数(高度)的数字类型要求,因此触发报错。

修正后的完整代码

ball = {}

function ball:load()
    self.x = love.graphics.getWidth() /2 
    self.y = love.graphics.getHeight() /2 
    self.width = 20
    self.height = 20  -- 修正拼写错误
    self.speed = 200 
    self.xvel = -self.speed
    self.yvel = 0
end 

function ball:update(dt)
    self:move(dt)
end

function ball:draw()
    love.graphics.rectangle("fill", self.x, self.y, self.width, self.height)
end

function ball:move(dt)
    self.x = self.x + self.xvel * dt
    self.y = self.y + self.yvel * dt
end

只需将self.hieght = 20改为self.height = 20,保证变量名拼写统一,即可解决该错误。

内容的提问来源于stack exchange,提问作者CreepyGoldenGaming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:05:20