• Create Account

## Separate two colliding rectangles

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

13 replies to this topic

### #1P0jahn  Members

Posted 23 June 2013 - 04:48 PM

I have two rectangles colliding, example:

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?

### #2Waterlimon  Members

Posted 23 June 2013 - 05:25 PM

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.

o3o

### #3dtkaos  Members

Posted 23 June 2013 - 08:05 PM

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.

### #4Edvinas Kilbauskas  Members

Posted 24 June 2013 - 02:18 AM

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, 26 June 2013 - 11:58 AM.

“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”― Nigel Marsh

### #5P0jahn  Members

Posted 24 June 2013 - 09:48 AM

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?

### #6Edvinas Kilbauskas  Members

Posted 24 June 2013 - 10:11 AM

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, 24 June 2013 - 10:12 AM.

“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”― Nigel Marsh

### #7P0jahn  Members

Posted 24 June 2013 - 05:56 PM

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

I will just google collision response.

### #8lithos  Members

Posted 24 June 2013 - 07:44 PM

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?

### #9Edvinas Kilbauskas  Members

Posted 25 June 2013 - 12:05 AM

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.

“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”― Nigel Marsh

### #10P0jahn  Members

Posted 26 June 2013 - 10:31 AM

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, 26 June 2013 - 10:33 AM.

### #11Edvinas Kilbauskas  Members

Posted 26 June 2013 - 11:51 AM

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, 26 June 2013 - 11:55 AM.

“There are thousands and thousands of people out there leading lives of quiet, screaming desperation, where they work long, hard hours at jobs they hate to enable them to buy things they don't need to impress people they don't like.”― Nigel Marsh

### #12marcClintDion  Members

Posted 27 June 2013 - 07:31 AM

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; }

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

Consider it pure joy, my brothers and sisters, whenever you face trials of many kinds, because you know that the testing of your faith produces perseverance. Let perseverance finish its work so that you may be mature and complete, not lacking anything.

### #13P0jahn  Members

Posted 30 June 2013 - 06:42 PM

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.

### #14marcClintDion  Members

Posted 30 June 2013 - 11:06 PM

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.

Consider it pure joy, my brothers and sisters, whenever you face trials of many kinds, because you know that the testing of your faith produces perseverance. Let perseverance finish its work so that you may be mature and complete, not lacking anything.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.