Difference between revisions of "BoundingBox.lua"

Line 5: Line 5:
 
<source lang="lua">
 
<source lang="lua">
 
-- Collision detection function.
 
-- Collision detection function.
-- Checks if a and b overlap.
+
-- Returns true if two boxes overlap, false if they don't
-- w and h mean width and height.
+
-- x1,y1 are the left-top coords of the first box, while w1,h1 are its width and height
function CheckCollision(ax1,ay1,aw,ah, bx1,by1,bw,bh)
+
-- x2,y2,w2 & h2 are the same, but for the second box
 
+
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
   local ax2,ay2,bx2,by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
+
   return x1 < x2+w2 and
  return ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1
+
        x2 < x1+w1 and
 +
        y1 < y2+h2 and
 +
        y2 < y1+h1
 
end
 
end
 
</source>
 
</source>
  
 
[[Category:Snippets]]
 
[[Category:Snippets]]

Revision as of 11:11, 17 November 2013

This script is used for Bounding Box Collision Detection. It will see if two rectangular objects over-lap. It returns true if there is a collision, and false otherwise.

This form of collision detection is not suited for games that have lots of circles and non-rectangular shapes, since the invisible space will be considered part of the collision rectangle. However, this should not be a problem for games such as Space Invaders clones.

-- Collision detection function.
-- Returns true if two boxes overlap, false if they don't
-- x1,y1 are the left-top coords of the first box, while w1,h1 are its width and height
-- x2,y2,w2 & h2 are the same, but for the second box
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