Error main.lua:138:尝试调用方法'checkCollision'(nil值)

问题描述 投票:0回答:1

我正在尝试在我正在制作的游戏的播放器文件中创建碰撞函数,但我不断收到此错误,并且不知道为什么。

这里是main.lua代码:

checkCollisions(enemies_controller.enemies, player.bullets)
player:checkCollision(enemies_controller.enemies)

这是我的Player.lua文件:

Player = Class{}


function Player:init(x, y, width, height)
 self.player = {}
 self.x = x
 self.y = y
 self.height = height
 self.dx = 0
 self.image = love.graphics.newImage('images/player.png')
 self.width = self.image:getWidth()
 self.fire_sound = love.audio.newSource('sounds/laser.wav', 'static')
 self.fire_sound:setVolume(.25)
 self.cooldown = 10
 self.bullets = {}
end

function Player:update(dt)
 self.x = self.x + self.dx * dt
 if self.x <= 0 then
     self.dx = 0
     self.x = 0
 end
 if self.x >= WINDOW_WIDTH - self.width * 4 then
     self.dx = 0
     self.x = WINDOW_WIDTH - self.width * 4
 end 
end

function Player:fire()
 if self.cooldown <= 0 then
     love.audio.play(player.fire_sound)
     if BULLET_COUNTER >= 1 then
         love.audio.stop(player.fire_sound)
         love.audio.play(player.fire_sound)
         self.cooldown = 30
         bullet = {}
         bullet.x = player.x + 25
         bullet.y = player.y + 5
         table.insert(self.bullets, bullet)
         BULLET_COUNTER = 0
         return
     end
     self.cooldown = 10
     bullet = {}
     bullet.x = self.x + 25
     bullet.y = self.y + 5
     table.insert(self.bullets, bullet)
     BULLET_COUNTER = BULLET_COUNTER + 1
 end
end

function Player:render()
 love.graphics.setColor(255, 255, 255)
 love.graphics.draw(player.image, player.x, player.y, 0, 4)
end

function checkCollision(enemies)
 for i,e in ipairs(enemies) do
     if e.x >= self.x and e.x + e.width <= self.x + self.width then
        table.remove(enemies, i)
        LIVES = LIVES - 1
     end
 end
end

我对LUA和LOVE2D还是很陌生,所以很多这样的代码可能非常琐碎,或者直截了当。我愿意接受任何批评!

love2d
1个回答
0
投票

欢迎使用Lua和Love2D!我相信该错误是因为您从未将函数checkCollision分配给Player类。将函数定义更改为:

function Player:checkCollision(enemies)
 for i,e in ipairs(enemies) do
     if e.x >= self.x and e.x + e.width <= self.x + self.width then
        table.remove(enemies, i)
        LIVES = LIVES - 1
     end
 end
end

应解决此错误。

© www.soinside.com 2019 - 2024. All rights reserved.