首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >错误main.lua:138:尝试调用方法'checkCollision‘( nil值)

错误main.lua:138:尝试调用方法'checkCollision‘( nil值)
EN

Stack Overflow用户
提问于 2019-12-05 12:40:20
回答 1查看 370关注 0票数 1

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

下面是main.lua代码:

代码语言:javascript
运行
复制
checkCollisions(enemies_controller.enemies, player.bullets)
player:checkCollision(enemies_controller.enemies)

这是我的Player.lua文件:

代码语言:javascript
运行
复制
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非常陌生,所以很多代码可能是非常琐碎的,或者是直接错误的。我愿意接受任何批评!!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-06 00:23:16

欢迎来到Lua和Love2D!我认为这个错误是因为您从未将函数checkCollision赋值给Player类。将您的函数定义更改为:

代码语言:javascript
运行
复制
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

应该可以修复这个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59188369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档