• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
P0jahn

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 biggrin.png 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 this post


Link to post
Share on other sites

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

I will just google collision response.

0

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0