Page 1 of 1

[Solved]Collision with map doesnt work

Posted: Mon Apr 24, 2017 2:17 pm
by Dzemal
Hello Guys,

So basically I am making a tile based "dungeon" game. After trying several times I couldn't get the collision in my game done. I want the rectangle to collide with the "1" on the tilemap. Hope you can help me.

Thanks in advance
-Dzemal

Re: Collision with map doesnt work

Posted: Mon Apr 24, 2017 6:10 pm
by OnACoffeeBreak
Seems like you are only checking the top left corner of your player for collisions. Here's code that checks all four player corners before updating player position. I'm pretty new to Lua and Love, so take this with a grain of salt. (.love is attached)

Code: Select all

function getMapTileFromWorldCoord(x, y)
  return map[math.floor(y / 32) + 1][math.floor(x / 32) + 1]
end

-- Return true if there's a map collision
function testMapCollision(x, y)
  -- Check player's four corners to see if they are on type 1 tile
  return (getMapTileFromWorldCoord(x, y) == 1 or
    getMapTileFromWorldCoord(x + 31, y) == 1 or
    getMapTileFromWorldCoord(x, y + 31) == 1 or
    getMapTileFromWorldCoord(x + 31, y + 31) == 1)
end    

function movement(dt)
    local dx = 0
    local dy = 0
    if love.keyboard.isDown("w") then dy = -player.speed * dt end
    if love.keyboard.isDown("s") then dy = player.speed * dt end
    if love.keyboard.isDown("a") then dx = -player.speed * dt end
    if love.keyboard.isDown("d") then dx = player.speed * dt end
    
    -- Before updating player's x coord, check if that would cause collisions
    if dx ~= 0 then
      -- Returns true if there are collisions
      if not testMapCollision(player.x + dx, player.y) then
        player.x = player.x + dx
      end
    end
    
    -- Before updating player's y coord, check if that would cause collisions
    if dy ~= 0 then
      -- Returns true if there are collisions
      if not testMapCollision(player.x, player.y + dy) then
        player.y = player.y + dy
      end
    end
end

Posted: Tue Apr 25, 2017 12:56 pm
by Dzemal
Thanks for the Help. Im actually pretty new to love2d too. Didn't program before. You probably know it better :D !

Re: Collision with map doesnt work

Posted: Tue Apr 25, 2017 1:04 pm
by OnACoffeeBreak
What I mean is that my changes seem to work, but it's likely there are better ways of doing this that I haven't learned yet.

Re: [Solved]Collision with map doesnt work

Posted: Tue Apr 25, 2017 2:14 pm
by Beelz

Code: Select all

-- Axis aligned bounding box(AABB) collision
-- Returns true if the rectangles overlap
function aabb(x1,y1,w1,h1, x2,y2,w2,h2)
	return x1 < x2 + w2 and
		x1 + w1 > x2 and
		y1 < y2 + h2 and
		h1 + y1 > y2
end

-- Same thing, but o1 and o2 are tables containing at least x, y, w, and h
function aabb2(o1, o2)
	return o1.x < o2.x + o2.w and
		o1.x + o1.w > o2.x and
		o1.y < o2.y + o2.h and
		o1.h + o1.y > o2.y
end