Advertisement
ForeverDev

Untitled

Nov 27th, 2014
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.23 KB | None | 0 0
  1. --general collision detection algorithm where x is posX, y is posY, sx is size x, sy is size y
  2. function isColliding(body1, body2)
  3.     return (
  4.         body1.x + body1.sx > body2.x and
  5.         body1.y + body1.sy > body2.y and
  6.         body2.x + body2.sx > body1.x and
  7.         body2.y + body2.sy > body1.y
  8.     )
  9. end
  10.  
  11. --example:  if isColliding(player, enemy) then ( ... ) end
  12.  
  13. --general algorithm to get colliding sides
  14. function edges(body1, body2)
  15.     local tolerance = 5 --define a tolerance: if the bodies are colliding and side x is within tolerance pixels of side y...
  16.     --return a tuple of booleans: left side, right side, top side, bottom side
  17.     return
  18.         body1.x + body1.sx - body2.x <= tolerance,
  19.         body2.x + body2.sx - body1.x <= tolerance,
  20.         body1.y + body1.sy - body2.y <= tolerance,
  21.         body2.y + body2.sy - body1.y <= tolerance
  22. end
  23.  
  24.  
  25.  
  26. --now these put together in an example:
  27.  
  28. function love:update(dt)
  29.     if isColliding(player, enemy) then --NOTE: you SHOULD make isColliding a method of player so u can do if player:isColliding(enemy), but it's not needed
  30.         local left, right, top, bottom = edges(player, enemy)
  31.         --left = true if the right side of player is touching left side of enemy, same for the rest
  32.         print(left, right, top, bottom)
  33.     end
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement