I'm trying to implement a aabb to circle collision.
Here's my code:
//From another file
radius = (sprite.width + sprite.height) / 4;
private function BoxToCircleCollision(box1:BoundingBox, circle1:BoundingCircle):Boolean
{
var nBoxMinX:Number = box1.sprite.x - box1.sprite.width / 2;
//var nBoxMinY:Number = box1.sprite.x + box1.sprite.width / 2;
var nBoxMaxX:Number = box1.sprite.y - box1.sprite.height / 2;
//var nBoxMaxY:Number = box1.sprite.y + box1.sprite.height / 2;
var nCirMinX:Number = circle1.sprite.x - circle1.radius / 2;
//var nCirMinY:Number = circle1.sprite.y - circle1.radius;
var nCirMaxX:Number = circle1.sprite.x + circle1.radius / 2;
//var nCirMaxY:Number = circle1.sprite.y + circle1.radius;
if (nBoxMaxX, 2 > nCirMinX))
{
Main.WriteDebug("Box max: " + nBoxMaxX + " | Circle min: " + nCirMinX);
return true;
}
else
{
Main.WriteDebug("Box max: " + nBoxMaxX + " | Circle min: " + nCirMinX);
return false;
}
}
Somehow the collision does work as expected. Either they never move at all and "collided" was traced, or they'll continue moving and never collide when I tried swapping values around.
Is there something i'm missing in my logic???
My box-box and circle-circle collision are working fine.
Thanks in advance for your help.
This row doesn't look at all correct:
var nBoxMaxX:Number = box1.sprite.y - box1.sprite.height / 2;
Maybe you meant this:
var nBoxMaxX:Number = box1.sprite.x + box1.sprite.width / 2;
This line won't compile:
if (nBoxMaxX, 2 > nCirMinX))
Edit:
Here's a function to help you get the AABB <-> Circle collision right. It's not a complete solution but you can combine it with the calculations you have for the AABB min and max values, should be trivial:
private function collideAABBandCircle(c : Circle, aabb:AABB) : Boolean {
var sqDist : Number = sqDist(c.centerPoint, aabb);
return sqDist <= c.radius * c.radius:
}
private function sqDist(p : Point, aabb:AABB) : Number {
/* CALCULATE min and max values of aabb bounds */
var sqDist : Number = 0.0;
if(p.x < minX) {
sqDist += (minX - p.x) * (minX - p.x);
}
if(p.x > maxX) {
sqDist += (p.x - maxX) * (p.x - maxX);
}
if(p.y < minY) {
sqDist += (minY - p.y) * (minY - p.y);
}
if(p.y > maxY) {
sqDist += (p.y - maxY) * (p.y - maxY);
}
return sqDist;
}