Loop Through Bodies and Only Destroy One Body
Posted: Wed Sep 28, 2022 4:47 pm
Hey everyone!
I'm trying to handle the collisions between the player and multiple enemies with collision callbacks. Here's how I add multiple enemies to the game:
Then, I can draw the enemies like this:
However, when I try to handle the collisions, when the player smashes down on the enemy, all of the enemies are destroyed, not just the single one he collided with. Why is that? Here's my code for that:
Here's the love file if you need it: (W, A, D to move, S to smash an enemy)
Thanks for any help!!
I'm trying to handle the collisions between the player and multiple enemies with collision callbacks. Here's how I add multiple enemies to the game:
Code: Select all
local allEnemies
function addEnemy(x,y)
enemy = {}
enemy.isHit = false
enemy.body = love.physics.newBody(world, x, y, "dynamic")
enemy.shape = love.physics.newRectangleShape(50, 100)
enemy.fixture = love.physics.newFixture(enemy.body, enemy.shape)
enemy.fixture:setUserData("Enemy")
table.insert(allEnemies, enemy)
end
function love.load()
allEnemies = {}
addEnemy(100, 0)
addEnemy(200, 0)
addEnemy(300, 0)
end
Code: Select all
for _, enemy in ipairs(allEnemies) do
if enemy.body:isDestroyed() == false then
love.graphics.polygon("fill", enemy.body:getWorldPoints(enemy.shape:getPoints()))
end
end
Code: Select all
function beginContact(a, b, coll)
for _, enemy in ipairs(allEnemies) do
if a:getUserData() == "Player" and b:getUserData() == "Enemy" and velY >= 1000 or a:getUserData() == "Enemy" and b:getUserData() == "Player" and velY >= 1000 then
player.jumps = 2
enemy.isHit = true
enemy.body:destroy()
end
if a:getUserData() == "Player" and b:getUserData() == "Enemy" and velY <= 1000 or a:getUserData() == "Enemy" and b:getUserData() == "Player" and velY <= 1000 then
player.isHit = true
end
end
end
Thanks for any help!!