Code: Select all
$polygon = array(
array(
"x" => 1,
"y" => 1
),
array(
"x" => 5,
"y" => 1
),
array(
"x" => 5,
"y" => 5
),
array(
"x" => 1,
"y" => 5
),
array(
"x" => 1,
"y" => 1
)
);
function direction($polygon) {
/*************************
If the area of an arbitrary
non-self-intersecting closed
polygon is positive the points
were ordered in a non clockwise
fashion, respectively clockwise
polygons have negative areas.
This is why the area algorithm usually
returns absolute values.
*************************/
$area = 0;
$n = count($polygon)-1;
for ($i=0;$i<$n;$i++) {
$j = ($i + 1);
$area += $polygon[$i]['x'] * $polygon[$j]['y'];
$area -= $polygon[$i]['y'] * $polygon[$j]['x'];
}
$area /= 2;
if ($area==0) {
return(false);
} elseif ($area > 0) {
return(1);
} elseif ($area < 0) {
return(2);
}
}
switch (direction($polygon) ) {
case false:
echo 'Your polygon foobar\'d';
break;
case 2:
echo 'CW';
break;
case 1:
echo 'CCW';
break;
}