Talking a little 'bout your current code:
- I think it might be better to each table inside your tilemap table to be all the same length or you may get some troubles or need to do some extra calculations ...
- Try reading a bit about code and variable scope. Some nice articles:
-
http://blogs.love2d.org/content/scope-within-lua
-
https://love2d.org/wiki/local
Back to the main problem...
You got you player's position, and also the its width and height, which is the same as any cell size from the tilemap.
So it being said, the area your player occupies is obviously that is from its position( x and y ) to its dimensions( w and h), so player.x+player.w and player.y+player.h;
Now we need to define which blocks or places we need to detect collision
Let's say we'll handle it with a table that holds the blocks positions which may collide:
Code: Select all
local cols = {}
cols[1] = {x=64, y=64}
cols[2] = {x=128, y=128}
So, each object of the table would be another table containing the positions of blocks that you want to detect collision.
Now we just need to calculate with the area before said is intercepting any of these blocks
Code: Select all
-- We define a function, it may be useful later for any other purposes
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2) -- Here we check if certain area transpass another area
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
-- We loop over all blocks stored at cols and check if the player hits it
for k, v in ipairs(cols) do
if CheckCollision(player.x, player.y, cellsize, cellsize, v.x, v.y, cellsize, cellsize) then
-- If the collides do any action here
end
end
Well, now you can do some callbacks whenever the player hits something. I've made some modifications to your code, and I'm going to attach it here. That's the basic.
Now the next step is a bit of work to do, which I'm not going to explain, but I got a reference for you:
https://www.gamedev.net/articles/progra ... nse-r3084/