Collision detection
Posted: Thu Nov 17, 2005 9:14 pm
Collision detection based on bounding box, you'll need your own functions to determine the bounding box.
Code: Select all
<?
class collision {
/*
USAGE
-----
$collision = new collision();
//Set box1
$box = array(
"xmin" => 100,
"ymin" => 100,
"xmax" => 250,
"ymax" => 250
);
$collision -> set_box(1,$box);
// Set box2
$box = array(
"xmin" => 50,
"ymin" => 50,
"xmax" => 100,
"ymax" => 100
);
$collision -> set_box(2,$box);
// Detect collision on two boxes
var_dump($collision -> detect(1,2));
*/
/* Array of boxes */
var $box;
/* Add box to array */
function set_box($number, $points) {
/* Set points */
$this -> box[$number]['upper_left']['x'] = $points['xmin'];
$this -> box[$number]['upper_left']['y'] = $points['ymin'] + ($points['ymax'] - $points['ymin']);
$this -> box[$number]['upper_right']['x'] = $points['xmax'];
$this -> box[$number]['lower_right']['y'] = $points['ymax'];
$this -> box[$number]['lower_left']['x'] = $points['xmin'];
$this -> box[$number]['upper_left']['y'] = $points['ymin'];
$this -> box[$number]['lower_right']['x'] = $points['xmin'] + ($points['xmax'] - $points['xmin']);
$this -> box[$number]['upper_right']['y'] = $points['ymin'];
}
function detect($one, $two) {
/* Box one */
$left1 = $this -> box[$one]['lower_left']['x'];
$right1 = $this -> box[$one]['lower_right']['x'];
$top1 = $this -> box[$one]['upper_left']['y'];
$bottom1 = $this -> box[$one]['lower_right']['y'];
/* Box two */
$left2 = $this -> box[$two]['lower_left']['x'];
$right2 = $this -> box[$two]['lower_right']['x'];
$top2 = $this -> box[$two]['upper_left']['y'];
$bottom2 = $this -> box[$two]['lower_right']['y'];
/* Detect if boxes are overlapping */
if ($left1 <= $left2) {
if ($right1 >= $left2) {
if ($top1 > $top2 && $top1 < $bottom2) {
return(true);
}
if ($bottom1 >= $top2 && $bottom1 <= $bottom2) {
return(true);
}
if ($bottom1 >= $bottom2 && $top1 <= $top2) {
return(true);
}
}
}
if ($left1 >= $left2 && $left1 <= $right2) {
if ($top1 >= $top2 && $top1 <= $bottom2) {
return(true);
}
if ($bottom1 >= $top2 && $bottom1 <= $bottom2) {
return(true);
}
if ($bottom1 >= $bottom2 && $top1 <= $top2) {
return(true);
}
}
return(false);
}
}
?>