I am trying to create little top view game with a character that moves around an open world. The world is filled with obstacles. I cannot figure out to handle my character position when he collides with corners of obstacles. I have the following onCollision method implemented, which ofcourse works just fine when the player hits a wall vertically or horizontally.
@override
void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
if (other is Wall) {
if (intersectionPoints.length == 2) {
var pointA = intersectionPoints.elementAt(0);
var pointB = intersectionPoints.elementAt(1);
final mid = (pointA + pointB) / 2;
final collisionVector = absoluteCenter - mid;
double penetrationDepth = (size.x / 2) - collisionVector.length;
collisionVector.normalize();
position += collisionVector.scaled(penetrationDepth);
}
}
super.onCollision(intersectionPoints, other);
}
However, when the character hits a corner, the way the penetration depth is calculated does not make sense, and therefor he gets stuck.
Any help on how to approach this problem would be greatly appreciated.
2
Answers
I solved it by figuring out how the intersection points work and determining the quadrant of the collision vector's direction. The smallest absolute displacement in either x or y direction determines from which side the player bumps into the corner. It works, so I am happy :). Still very curious if a math wizz could do this without all these assumptions, and use some clever vector tricks.
First time I try something for the game in Flutter. Could you please try this code for your need?