Difference between revisions of "BoundingBox.lua"

m (linkification)
Line 5: Line 5:
 
<source lang="lua">
 
<source lang="lua">
 
-- Collision detection function.
 
-- Collision detection function.
-- Checks if box1 and box2 overlap.
+
-- Checks if a and b overlap.
 
-- w and h mean width and height.
 
-- w and h mean width and height.
function CheckCollision(box1x, box1y, box1w, box1h, box2x, box2y, box2w, box2h)
+
function CheckCollision(ax1,ay1,aw,ah, bx1,by1,bw,bh)
    if box1x > box2x + box2w - 1 or -- Is box1 on the right side of box2?
+
 
      box1y > box2y + box2h - 1 or -- Is box1 under box2?
+
  local ax2,ay2,bx2,by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
      box2x > box1x + box1w - 1 or -- Is box2 on the right side of box1?
+
  return ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1
      box2y > box1y + box1h - 1    -- Is b2 under b1?
 
    then
 
        return false                -- No collision. Yay!
 
    else
 
        return true                -- Yes collision. Ouch!
 
    end
 
 
end
 
end
 
</source>
 
</source>
  
 
[[Category:Snippets]]
 
[[Category:Snippets]]

Revision as of 19:35, 30 October 2011

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.
-- Checks if a and b overlap.
-- w and h mean width and height.
function CheckCollision(ax1,ay1,aw,ah, bx1,by1,bw,bh)

  local ax2,ay2,bx2,by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
  return ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1
end