Search code examples
love2d

I don't know how to get basic collision working


I'm new to Love2D and Lua but so far it's been going well. I'm trying to make a simple game but so far I haven't been able to find anything on collision besides having the player not scroll of screen. I've been trying to use this

function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and
     x2 < x1+w1 and
     y1 < y2+h2 and
     y2 < y1+h1
end

But I'm not entirely sure how to use it as each time I tried nothing in the program changed. Please help?

I'm not too familiar with this site, sorry. I changed it but it still doesn't work.

tree = {x = 20, y = 20, speed = 0, img = nil }

tree.img = love.graphics.newImage("assets/tree.png")

function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
  return x1 < x2+w2 or
     x2 < x1+w1 or
     y1 < y2+h2 or
     y2 < y1+h1
end

function tree_update(dt)
    if CheckCollision(crs.x, crs.y, crs.img:getWidth(), crs.img:getHeight(),    tree.x, tree.y, tree.img:getWidth(), tree.img:getHeight()) then
    love.graphics.print("It touched the thing", love.graphics:getWidth()/2-        50, love.graphics:getHeight()/2-10)
   end
   end

   function tree_draw()
    love.graphics.draw(tree.img, tree.x, tree.y)
   end

Solution

  • The return statement should be using or instead of and as you want it to return that it has collided when any of the statements are true.

    function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
      return x1 < x2+w2 or
         x2 < x1+w1 or
         y1 < y2+h2 or
         y2 < y1+h1
    end
    

    There's also a collision feature in Love2D called "Contacts" that may help with things like collisions.