The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

game development- collision detection question

hello.
I am working on a strategy game, and i made a few models of collisions between rectangles in the past but now i need it to be precise and the code to be versatile.
i am not going to show you all my 8 classes, because you're not gonna read them . so, i will simplify it to that:
i have two rectangles, rectangle 1: player, rectangle 2: wall. (doesn't really matter)
every frame, i call the method:

and i want it to return right/left/up/down/none. for example, if rectangle 1 collides rectangle 2 from above, it will return up. if it doesnt collide at all, it'll return none.

can you please show me example code, or tell me the theories behind this? i dont have a problem when it is just a big wall, but when it can collide from all directions.... it gets a little harder, especially when Y axis is f***ing in the wrong direction!.
I want it to be good. for example, there are two rectangle colliding horizontally. the left one is controlled by a human, and is moving right AND up. when the rectangle reaches above the other one, it should not jump some distance up or right but smoothly continue moving. it depends on other things, but on this too!
by the way, what do you recommend doing when it does collide and if i detect it? make speed=0 and return the x or y location to the limit of collision?

Re: game development- collision detection question

Java has a "contains" method you may make use of, depending on what you have done in the implementation so far, just a note

You can short circuit some of the testing away, possibly.
Say object A who has size s1, and object B who has size s2. Draw an imaginary line from the center points of the two. When the distance from the two center points is a certain length, the two can not intersect, and when it is under a certain length they have to intersect. This type of optimization helps with code that shows many more misses than collisions because in one test you avoid the group of corner testing. Profile the code. A quick glance should give clues. How many objects are being tested vs how many you expect to collide. For example a ball breaking bricks game, testing the ball against every brick on the screen, you expect there to be far more misses than collisions.

Similarly in such a game, you can avoid testing ALL bricks if you check to see if the ball's upper limit is under the lowest brick's lower limit. Or if the ball was on the lower half of the screen. Or test only the left or right half of the screen. Or just the upper quarter. Again, profile the application and see where all the time is being spent and try to omit testing if it makes sense.

No, no one would read 8 classes. Well someone might just because we said no one would. But you can post relevant methods and code snippets showing how you implement collision, positioning, movement etc.. what ever seems related. If you have any questions post the needed parts
Good luck

Re: game development- collision detection question

you are right, i should really have thought about it... not spending efficiency of program on such things as checking collision between far objects, thanks.
you didnt answer my question, though: how do i detect a collision between two rectangles? it is the main problem i am working on now.
thanks anyway

Re: game development- collision detection question

Originally Posted by david37370

how do i detect a collision between two rectangles?

How would you detect two rectangles colliding if you were to draw them out on a 2d grid? Did you look at the contains method i mentioned?
There are too many possible variations to just write a sample that fits your program. You have to consider all the factors (which are not listed here) to come up with the best collision detection for your needs. If you need more help post more of the code you are using and explain what problems you are having. Include profiling results and/or a SSCCE

Re: game development- collision detection question

contains is helpful if i am trying to check if there is a rectangle INSIDE an other rectangle, which is not collision detection. you said, "depending on what you have done in the implementation so far", which is wrong, that is the reason i didnt post the whole program: the function gets the locations and sizes, and return right/left/up/down/none. so i dont need to post more of the code, because it should not affect this function.
just asked for code/explantion! XD

Re: game development- collision detection question

contains is an overloaded method in the Rectangle class. You can also look for a Point or, x,y representing a location, is within the bounds of a rectangle (and more). Again, not that you should or should not use it, my suggestion is to use it as a tool to understand how to detect collision.

Re: game development- collision detection question

Allrighty now, i made some progress: realised there is the Rectangle.intersects() method! god it is gonna save me so much headache (thought it feels like cheating ).
so now, i made two rectangles: rect1, rect2. gave them x1 ,y1 ,x2 ,y2 coordinates and width1, height1, width2, height2 size. now i do:

if (rect1.intersects(rect2)){
double distancex=Math.abs(x1-x2);
double distancey=Math.abs(y1-y2);
if (distancex>distancey){
if (x1>x2){
return "left";
}
else {
return "right";
}
}
else if (distancey>distancex){
if (y1>y2){
return "down";
}
else {
return "up";
}
}
}
I think it is right, if you notice something wrong there, please tell.
i have another problem now: what should i do when i get the direction? i mean, say it returned "up". so now i do:
vy1=0; y1=y1-vy1;
or maybe:
vy1=0; y1=y2-height2;
i am not very experianced at this. help is greatly appreciated.
thanks!

Re: game development- collision detection question

i have another problem now: what should i do when i get the direction?

It's not clear to me what the direction means from your logic, but I'll answer generally.

Consider one rectangle that moves in a blank area that collides with the top, bottom, right, or left sides of the area. When the rectangle is moving left and collides with the left side, a change of direction is determined, usually in the direction of a reflection ray. If the rectangle is moving PURE LEFT before the collision, the reflection ray would be PURE RIGHT, or

deltaX = -deltaX, and
deltaY = deltaY = 0

If there is both a deltaX and deltaY component to the rectangle's movement before the collision - still a LEFT COLLISION - then the reflection ray is:

deltaX = -deltaX, and
deltaY = deltaY.

In other words, the shift in the X direction, previously to the left, becomes an X shift to the right, and the shift in the Y direction continues in the same direction as it was before the collision.

Draw the pictures and write down similar results for collisions to the top, right, and bottom of the area in which the rectangle is moving. Then, after you understand that and have the basic equations worked out, consider how TWO rectangles colliding should act. The easy cases are when two rectangles traveling in opposite directions collide. In those cases (assuming the simplest results), the rectangles simply change direction. What if the two rectangles are not traveling in opposite directions? How should the direction of one influence the direction of the other and vice versa?

There are other physics to the problem to consider, but start with the simple cases and add the effects of physics later, if you care.

Re: game development- collision detection question

thanks for the detailed reply!
i tried the code i posted above, and it determines the collision direction fine, according to the first rectangle.
now, i dont know how to respond to the collision: i tried several things, like making speed=0 and returning the block to its previous location, but they dont work.
maybe it is because of something i have in my program- each block (player, unit, whatever) has a location x and y, AND destinationx, destinationy. each block gets vx and vy according to the destination, and that works fine. but maybe it makes the collision not work... i'll keep trying

i think that when there are 2 moving things colliding, i have to check collisions, and after i checked them all then respond to each of them. that way, they both collide and not only one of them.

Re: game development- collision detection question

i dont know how to respond to the collision

I tried to explain that but perhaps missed what I thought was obvious: the collision responses I outlined are changes to the existing animation. If the existing animation is moving an object to the right, change the animation so that the object moves to the left after a collision, usually by varying the deltaX:

// the Timer's run() method animates object's in the component's scene
run()
{
// . . . all before stuff
// move the object in the desired direction during one timeframe
// and repaint the scene to show the results.
object.setX( deltaX );
object.setY( deltaY );
repaint();
// . . . . all after stuff
}

Re: game development- collision detection question

no... maybe i didnt explain myself at the beginning. i dont want the objects to change direction, but to simply stop (vx=0 or vy=0, according to collision direction). and not only stop, but stop the intersection between them somehow-i was thinking about just moving them... without moving them too far.
for example, there are 3 rectangles,
rect 1: x=0, width=1
rect 2: x=1, width=1
rect 3: x=3, width=1

and rect 2 is moving between them in the y axis. i want it to move, and not get stuck. and if you press rigt or left, it just doesnt move, because collision makes vx=0 and returns the rectangle to its proper position. a problem. i'm stilll thinking ^^

--- Update ---

no... maybe i didnt explain myself at the beginning. i dont want the objects to change direction, but to simply stop (vx=0 or vy=0, according to collision direction). and not only stop, but stop the intersection between them somehow-i was thinking about just moving them... without moving them too far.
for example, there are 3 rectangles,
rect 1: x=0, width=1
rect 2: x=1, width=1
rect 3: x=3, width=1

and rect 2 is moving between them in the y axis. i want it to move, and not get stuck. and if you press rigt or left, it just doesnt move, because collision makes vx=0 and returns the rectangle to its proper position. a problem. i'm stilll thinking ^^

Re: game development- collision detection question

You're right, you didn't explain it well at the beginning or at any other point, including this one. If you have a short runnable example of code that's not working right, post it and explain what you want it to do. We've reached the limit of what can be done talking theory, and it's time to move to application.