我正在尝试为正在制作的游戏在播放器文件中添加碰撞功能,但我不断收到此错误,并且不知道为什么。
这是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还是很陌生,所以很多这样的代码可能非常琐碎,或者直接出错。我愿意接受任何批评!
答案 0 :(得分: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
应解决此错误。