44 minutes ago, Zakwayda said:Does that code work? Or is the behavior still incorrect?
Hi Zakwayda!
Yeah that implementation solved my problem, I can slide, because it checks the collision in terms of collision deep.
My actually code is this one,
... move method ...
Direction collisionDirection = Direction.NONE;
// Check collisions
for (Rectangle mapCollider : belongsToLevel.tiledMap.mergedColliders) {
if (collider.intersects(mapCollider)) {
collisionDirection = MathUtils.getRectangleDepthSideCollision(collider, mapCollider);
break;
}
}
if (direction == Direction.NORTH && collisionDirection == Direction.NORTH
|| direction == Direction.SOUTH && collisionDirection == Direction.SOUTH) {
pos.x += xMove;
}
else if (direction == Direction.WEST && collisionDirection == Direction.WEST
|| direction == Direction.EAST && collisionDirection == Direction.EAST) {
pos.y += yMove;
}
else {
pos.x += xMove;
pos.y += yMove;
}
} // Move method ends
// Collision method in MathUtils.java
/**
* Gets the side of collision in depth between two rectangles.
* @param collider
* @param obstacle
* @return
*/
public static Direction getRectangleDepthSideCollision(final Rectangle collider, final Rectangle obstacle) {
int dx = (collider.x + collider.width / 2) - (obstacle.x + obstacle.width / 2);
int dy = (collider.y + collider.height / 2) - (obstacle.y + obstacle.height / 2);
int width = (collider.width + obstacle.width) / 2;
int height = (collider.height + obstacle.height) / 2;
int crossWidth = width * dy;
int crossHeight= height * dx;
// Detect if is collision (done with intersects)
//if (Math.abs(dx) <= width && Math.abs(dy) <= height) {
if (crossWidth > crossHeight) {
if (crossWidth > -crossHeight) {
System.out.println("Top!");
return Direction.NORTH;
}
else {
System.out.println("Right!");
return Direction.EAST;
}
} else {
if (crossWidth > -crossHeight) {
System.out.println("Left!");
return Direction.WEST;
}
else {
System.out.println("Bottom!");
return Direction.SOUTH;
}
}
}
I am very grateful for your help