Followers 0

# Separate two colliding rectangles

## 13 posts in this topic

I have two rectangles colliding, example:

[attachment=16452:example.png]

In this example, it would be wise to push the red rectangle to the left or the green to the right.

How do we code this? How would we know which direction to push? Pushing strength?

0

##### Share on other sites
You would push both rectangles in a ratio that makes sense given their masses. Pushing strength should be high enough to cancel the forces pushing in, and also separate them in case they already interpenetrated by some amount. Just google for collision response and you'll find plenty of resources.
0

##### Share on other sites

My first question is do you have any type of collision in place at the moment? If so, let take a look at the code; if not I would google some collision detection basics. Easiest way to make the objects repel is to multiply their velocity by -1 so it reverses the direction.

I think some code example will help determine more of what is going on.

0

##### Share on other sites

Somewhere on the internet I found this, and saved into .txt file on my computer. Here's what it says:

1. After applying movement, check for and resolve collisions.
2. Determine the tiles the player overlaps based on the player's bounding box.
3. Iterate through all of those tiles doing the following: (it's usually not very many unless your player is huge compared to your world tiles)
1. If the tile being checked isn't passable:
1. Determine how far on the X and Y axes the player is overlapping the non-passable tile
2. Resolve collision by moving the player out of that tile only on the shallow axis (whichever axis is least penetrated)
• For example, if Y is the shallow axis and the collision is below, shift the player up to no longer overlap that tile.
• Something like this: if(abs(overlap.y) < abs(overlap.x)) { position.y += overlap.y; } else { position.x += overlap.x; }
3. Update the bounding box's position based on the player's new position
4. Move on to the next tile...
2. If the tile being checked is passable, do nothing
4. If it's possible that resolving a collision could move the player into another collision, you may want to run through the above algorithm a second time. Or redesign your level.

So I implemented this algorithm, and it works perfectly fine!

It should look something like this:

public void handleCollisions(GameObject player){

for(int i = 0; i < levelObjects.size(); i++){
GameObject tile = levelObjects.get(i);

if(tile.collidesWith(player)){
float overX = ((player.width+tile.width)/2.0)-Math.abs(player.x-tile.position.x);
float overY = ((player.height+tile.height)/2.0)-Math.abs(player.y-tile.position.y);

if(overY > overX){
if(player.x > tile.position.x)
player.move(overX,0);
else
player.move(-overX,0);
}else{
if(player.velocity.y > 0.0)
player.move(0,-overY);
else
player.move(0,overY);
}
}
}


You should run this after the player position was updated.

Edited by Edvinas Kilbauskas
2

##### Share on other sites

Thanks all.

Edvinas Kilbauskas, thanks, I will test your code. You are using a variable named obj, what do that var represent?

Also, could I replace velocity.y with movespeed? Or could I use my current Y - the previous Y as velocity?

0

##### Share on other sites

Thanks all.

Edvinas Kilbauskas, thanks, I will test your code. You are using a variable named obj, what do that var represent?

Also, could I replace velocity.y with movespeed? Or could I use my current Y - the previous Y as velocity?

Oh crap I was renaming my original code to make it more readable, but I forgot to delete and rename few things. I will fix it right now.

Edit: FIXED! :)

Edited by Edvinas Kilbauskas
0

##### Share on other sites

Thanks!  Not working though. Maybe because I dont have a velocity variable.

I will just google collision response.

0

##### Share on other sites

We need to know a lot more about your game to do anything useful.

Is your game tile based?  Are they rectangles on coordinates?  something else?

0

##### Share on other sites

Thanks!  Not working though. Maybe because I dont have a velocity variable.

I will just google collision response.

What's not working? What exactly is happening? Also the postition.x coordinates are centered, and not top left just so you know.

Also you don't have to use velocity if your game isn't platformer, because I use it to know if player is falling or jumping.

I don't know anything about your game so it's hard to tell what the problem may be.

0

##### Share on other sites

It is a plattformer, but only characters with gravity use velocity x and y, the other ones use movespeed. Most shapes are rectangles.

public class MovableObject extends GameObject
{
public void collisionRespone(MovableObject target)
{
if(isColliding(target))
{
float centerX = currX + width / 2;
float centerY = currY + height / 2;

double overX = ((target.width  + width ) /  2.0) - Math.abs(target.currX - centerX);
double overY = ((target.height + height) /  2.0) - Math.abs(target.currY - centerY);

if(overY > overX)
{
if(target.currX > centerX)
target.currX += overX;
else
target.currX -= overX;
}
else
{
float vy = target.currY - target.getPrevY(); //vy is a positive value if we are falling.

if(vy > 0)
target.currY -= overY;
else
target.currY += overY;
}
}
}
}


currX and currY is the topleft corner and its current position in the game.

The code is not working, they still overlap.

Edited by P0jahn
0

##### Share on other sites

What exactly is "MovableObject target" variable? Is it a tile, or another moving character? Also, I think you should replace everything to this:

public class MovableObject extends GameObject
{
public void collisionRespone(MovableObject target)
{
if(isColliding(target))
{
float centerX = currX + width / 2;
float centerY = currY + height / 2;

double overX = ((target.width  + width ) /  2.0) - Math.abs(target.currX - centerX);
double overY = ((target.height + height) /  2.0) - Math.abs(target.currY - centerY);

if(overY > overX)
{
if(this.currX > centerX){
this.velocity.x = 0;
this.currX += overX;
}
else
this.velocity.x = 0;
this.currX -= overX;
}
else
{
float vy = this.currY - this.getPrevY(); //vy is a positive value if we are falling.

if(vy > 0){
this.velocity.y = 0;
this.currY -= overY;
}
else{
this.velocity.y = 0;
this.currY += overY;
}
}
}
}
}


I should tell you, that the object which you are passing to this function should be static, like ground tile, not movable object, at least just for now, to check if everything is working all right.

Secondly, I didn't know that it was a platformer, so now I fixed the code above, that when you colliding the with ground, we set velocity.y to zero, because whats the point of moving the object back, it if the velocity will keep getting bigger, and bigger until it's velocity is so huge, that it passes your obstacle in one frame, and can't check if it is collided or not.

You should put a vector in your GameObject class representing velocity, because as of now I see you don't have one. And each frame you will add that velocity to your players position like this:

currX += velocity.x;
currY += velocity.y;
Edited by Edvinas Kilbauskas
0

##### Share on other sites

Are you running a collision test before running the collision response function that's being shown above?  The function above won't do anything to help you detect a collision and it wont even run unless isColliding(target)  is set true by a collision detection algorithm.

I apologize if I sound insulting for asking such a question, but since this issue hasn't been resolved yet I thought I'd confirm the basic's.

Do you have something like the following that is setting isColliding(target) = true.

This is the basic formula for detecting two overlapping bounding boxes.  It will help to cut out two squares of paper and write the variable names on the edges of the two pieces of paper so you can verify it and understand why it works.

//==================================================================================================================

if((player_rightEdge >= target_leftEdge) && (target_rightEdge >= player_leftEdge) && (player_TopEdge >= target_bottomEdge) && (target_topEdge >= player_BottomEdge)) {       isColliding(target) = true; }

//=================================================================================================================================

0

##### Share on other sites

Edvinas Kilbauskas: target is a movable game entity, not a tile. The entire purpose of this function, collisionRespone, is to separate two colliding entities. Is that what your function do? Just wanna make sure we are coding the same thing.

0

##### Share on other sites

The code he posted definitely separates two objects that have collided.  I was able to implement it and I'm quite happy with the results, objects are no longer getting stuck together.

currX and currY is the topleft corner and its current position in the game.

It's hard to tell what info you are feeding into that function but the following looks like a problem according to what you said.

The variable that is highlighted blue has been adjusted from the topLeft to be at the center I don't see a similar adjustment for target.currX

double overX = ((target.width + width ) / 2.0) - Math.abs(target.currX - centerX);

It looks like some of the variables are aligned for the top left corners and some are aligned to the centers.

0

## Create an account

Register a new account

Followers 0

• 10
• 28
• 14
• 11
• 33