I have been following the this guide to implement this. My current implementation is the following:
class SAT {
SAT();
bool collides(Rectangle rect1, Rectangle rect2){
var axises = [
rect1.topRight-rect1.topLeft,
rect1.topRight-rect1.bottomRight,
rect2.topLeft-rect2.bottomLeft,
rect2.topLeft-rect2.topRight
];
for(var axis in axises){
Projection p1 = project(axis,rect1);
Projection p2 = project(axis,rect2);
if(!overlap(p1,p2)){
return false;
}
}
return true;
}
Projection project(Position axis, Rectangle rect){
Position projection = getProjectionPosition(axis,rect);
Collection<Position> corners = [rect.topLeft,rect.topRight,rect.bottomRight,rect.bottomLeft];
num min = dot(projection,corners[0]);
num max = min;
for(var i = 1; i < corners.length; i++){
num p = dot(projection,corners[i]);
if(p < min){
min = p;
}else if(p > max){
max = p;
}
}
return new Projection(min,max);
}
bool overlap(Projection p1, Projection p2){
return p1.max >= p2.min && p1.min <= p2.max;
}
num dot(Position projection, Position point){
return projection.x*point.x + projection.y*point.y;
}
Position getProjectionPosition(Position axis, Rectangle rect){
num p = (rect.topRight.x*axis.x+rect.topRight.y*axis.y)/(Math.pow(axis.x, 2)+Math.pow(axis.y, 2));
Position projected = new Position(p*axis.x,p*axis.y);
return projected;
}
}
However this doesn't seem to work. I think I might be a bit confused about the getProjectionPosition
algorithm, as you can see I always use rect.topRight
. But maybe I am supposed to loop trough all the corners of the rectangle? or should it just be the corner belonging to this axis? The guide wasn't very clear on this.
Any ideas on whats wrong? Or is there a reference implementation I could look at to see how my implementation differs?