在我的游戏雕像中,如果我的对象是这样的,我会创建一个实例
function PlayState:enter(params)
self.paddle = params.paddle
self.bricks = params.bricks
self.health = params.health
self.score = params.score
self.highScores = params.highScores
self.level = params.level
self.recoverPoints = 5000
self.extendPoints = 7000
-- give ball random starting velocity
self.inPlayBalls= AllBalls(params.ball)
self.inPlayBalls[1].dx = math.random(-200, 200)
self.inPlayBalls[1].dy = math.random(-50, -60)
end
AllBalls类是一个类似的简单类
AllBalls = Class{}
function AllBalls:init(p)
self.ball=p
self.inPlayBalls={self.ball}
end
function AllBalls:update(dt,target)
for k, ball in pairs(self.inPlayBalls) do
ball:update(dt)
if ball:collides(target) then
-- raise ball above paddle in case it goes below it, then reverse dy
ball.y = target.y - 8
ball.dy = -target.dy
--
-- tweak angle of bounce based on where it hits the paddle
--
-- if we hit the paddle on its left side while moving left...
if ball.x < target.x + (target.width / 2) and target.dx < 0 then
ball.dx = -50 + -(8 * (target.x + target.width / 2 - ball.x))
-- else if we hit the paddle on its right side while moving right...
elseif ball.x > target.x + (target.width / 2) and target.dx > 0 then
ball.dx = 50 + (8 * math.abs(target.x + target.width / 2 - ball.x))
end
gSounds['paddle-hit']:play()
end
if math.abs(ball.dy) < 150 then
ball.dy = ball.dy * 1.02
end
if ball.remove then
table.remove(self.AllBalls, k)
end
end
end
function AllBalls:collides(target)
for k, ball in pairs(self.inPlayBalls) do
if ball:collides(target) then
if ball.x + 2 < brick.x and ball.dx > 0 then
-- flip x velocity and reset position outside of brick
ball.dx = -ball.dx
ball.x = brick.x - 8
-- right edge; only check if we're moving left, , and offset the check by a couple of pixels
-- so that flush corner hits register as Y flips, not X flips
elseif ball.x + 6 > brick.x + brick.width and ball.dx < 0 then
-- flip x velocity and reset position outside of brick
ball.dx = -ball.dx
ball.x = brick.x + 32
-- top edge if no X collisions, always check
elseif ball.y < brick.y then
-- flip y velocity and reset position outside of brick
ball.dy = -ball.dy
ball.y = brick.y - 8
-- bottom edge if no X collisions or top collision, last possibility
else
-- flip y velocity and reset position outside of brick
ball.dy = -ball.dy
ball.y = brick.y + 16
end
end
end
end
function AllBalls:add(ball)
local newBall=Ball(ball.skin)
newBall.x=ball.x
newBall.dx=math.random(-200,200)
newBall.y=ball.y
newBall.dy=ball.dy
table.insert(self.inPlayBalls, newBall)
end
function AllBalls:out()
for k, ball in pairs(self.inPlayBalls) do
if ball.y >= VIRTUAL_HEIGHT then
ball.remove=true
end
end
end
当我进入播放状态时,我会得到以下错误
src/states/PlayStatue.loa:37尝试索引零值
我是卢阿的新手,我可能犯了一个愚蠢的错误,我找不到,所以任何帮助都会通知
问题可能来自此分配
self.inPlayBalls= AllBalls(params.ball)
从您的GitHub来看,inPlayBalls
是AllBalls
实例的一个属性。这意味着您必须首先创建AllBalls
实例,然后获取属性以将其分配给变量,如以下所示:
self.allBalls = AllBalls(params.ball)
self.inPlayBalls = self.allBalls.inPlayBalls