Difference between revisions of "BoundingBox.lua"

(added to Category:Snippets)
m (linkification)
Line 1: Line 1:
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 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.
 
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.

Revision as of 09:03, 15 September 2010

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 box1 and box2 overlap.
-- w and h mean width and height.
function CheckCollision(box1x, box1y, box1w, box1h, box2x, box2y, box2w, box2h)
    if box1x > box2x + box2w - 1 or -- Is box1 on the right side of box2?
       box1y > box2y + box2h - 1 or -- Is box1 under box2?
       box2x > box1x + box1w - 1 or -- Is box2 on the right side of box1?
       box2y > box1y + box1h - 1    -- Is b2 under b1?
    then
        return false                -- No collision. Yay!
    else
        return true                 -- Yes collision. Ouch!
    end
end