Search code examples
luatilelove2d

Tile Collision Detection


So, I have been working on this game for a bit. However, over the past day I have not been able to figure out how to work my collision detection.

The scale at default is equal to 2.

The player is 41*scale by 64*scale.

My player is centered in the middle of the screen in both the x and y axis.

Since the player is centered the world is what moves, those variables are worldx and worldy. The player always stays at the center of the screen.

My tile map is stored in an array and is based on the image pixel color. If the pixel is white at map[x][y] the value is set to 0 else it's set to the block. Meaning the block does not get rendered.

for x = 0, w-1 do --scans the image and builds the map array
   amap[x] = {}
   for y = 0, h-1 do
      local r, g, b, a = source:getPixel(x, y)
      if r == 255 and g == 255 and b == 255 then
         block = 0
      end
      if r == 255 and g == 100 and b == 0 then
         block = 1
      end
      if r == 130 and g == 125 and b == 0 then
         block = 2
      end
      if r == 76 and g == 76 and b == 76 then
         block = 3
      end
      if r == 255 and g == 0 and b == 255 then
         --this is the spawn pixel yet to build
      end
      amap[x][y] = block
   end
end --end function

function that draws the map

for x = 0, w-1 do --draws the map
   for y = 0, h-1 do
      if amap[x][y] ~= 0 then
         love.graphics.drawq(ImgBlocks, Blocks[amap[x][y]], 32*x*(3/bscale) + worldx, 32*y*(3/bscale) + worldy + jy, 0 , 3/bscale, 3/bscale)
      end
      if amap[x][y] == 4 then  
      end
   end
end --end function

The function needs to return true or false base on if there is collision between player and block.


Solution

  • Your tiles are 32x32, correct? (from the drawq call) I would recommend you make a function that checks if a point is in a solid tile:

    function pointCollisionTest(x, y)
        -- find which tile the point is in
        local tx, ty = math.floor(x / 32), math.floor(y / 32)
        -- check the tile
        if map[tx][ty] == solid then
            return true
        else
            return false
        end
    end
    

    You'll have to change the if map[x][y] == solid logic based on how you determine solid tiles, but this code should otherwise work.

    Once you have point collision, the way you make the player collide is by checking each corner of its hitbox (which you should easily be able to determine) against this function whenever the player moves. There are a few ways to do this; I use the relatively simple method of calculating the player's new position, testing it, then canceling the move entirely if the collision test returns true. You have to check/cancel the x and y components of the move separately, though, so the player can move along walls instead of sticking to them.