Hi, welcome to the forums!
I see your code is very well commented, I like that
The reason why you're getting a "hit" every frame is that you're calling the collision detection the wrong way:
Code: Select all
--spike hit box
insidebox(playerx, playery, spikex, spikey, 45, 51)
if insidebox then
print("hit")
end
What you're doing there is
1- calling the insidebox function, but it doesn't really do anything, because there's nothing receiving what it returns
2- checking if insidebox exists. Well, insidebox exists, so hit hit hit hit hit hit hit...
What you want to do is:
Code: Select all
--spike hit box
if insidebox(playerx, playery, spikex, spikey, 45, 51) then
print("hit")
end
Now the the "if" is checking insidebox's result, not insidebox itself.
But the hit detection is still weird, and this is why:
Code: Select all
--draw the spike
for i=1,spiketotal do
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(spike, spikex+i*102, spikey)
end
You're drawing the spike in one place, different from the place where it really is. You should change the spikex somewhere else, not misplace it in the draw function. This would be correct:
Code: Select all
--draw the spike
for i=1,spiketotal do
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(spike, spikex, spikey)
end
And now the collision is making some sense, but there's still one problem. You're only detecting collision for the player's origin (its uppermost left corner, in this case). Let's change the insidebox function so that it detects collision for all four corners of the player:
Code: Select all
function insidebox(px, py, x, y, wx, wy)
local playerwidth = 53
local playerheight = 60
if (px > x and px < x + wx)
or (px + playerwidth> x and px + playerwidth < x + wx) then
if (py > y and py < y + wy)
or (py + playerheight > y and py + playerheight < y + wy) then
return true
end
end
return false
end
That's much better! Now you might think the hitbox might be a bit large... It is advised for platformers and stuff to keep hitboxes of things that hurt the player a bit smaller than the sprite size. I think you can try to tweak that yourself, but feel free to come back here if you have any more problems.