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
[Solved]Collision with map doesnt work
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
[Solved]Collision with map doesnt work
- Attachments
-
- game.love.zip
- This is the game i talked about.
- (14.2 KiB) Downloaded 121 times
Last edited by Dzemal on Tue Apr 25, 2017 1:24 pm, edited 1 time in total.
- OnACoffeeBreak
- Prole
- Posts: 28
- Joined: Tue Apr 11, 2017 11:19 am
Re: Collision with map doesnt work
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
- Attachments
-
- game.love
- (15.79 KiB) Downloaded 123 times
- OnACoffeeBreak
- Prole
- Posts: 28
- Joined: Tue Apr 11, 2017 11:19 am
Re: Collision with map doesnt work
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
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
Who is online
Users browsing this forum: Bing [Bot], Google [Bot] and 2 guests