Reputation: 158
So basically im trying to figure out how to make a proper collision between two Rectangles. Detecting isn't the problem, but the rectangles begin to clip. I wanted to reset the position, but how do I do that. I'm trying to use dx and dy to reset, but it won't reset to the right coordinates.
https://i.sstatic.net/IU6sK.png (Sorry I can't use images yet)
System.out.println(this.y + this.h + " " + e.getY());
if(this.y + this.h >= e.getY())
{
if(this.dy > 0)
{
this.y -= delta * this.dy + 0.1;
this.dy = 0;
}
else
{
this.y += delta * this.dy;
this.dy = 0;
this.inAir = false;
}
}
This code is just an example to show how I am trying it for the top. (this = the white Rectangle and e = the orange one) I used my class Entity, which extends Rectangle.
I'm checking intersection before I call this. This is a function in the "white" Entity and the intersection is checked in the update function of the main loop.
If I use this, there is like 1px between the rectangles. Any ideas? Thanks for any help :)
Upvotes: 4
Views: 287
Reputation: 419
The best way to do rectangular collision is to use the Rectangle
class to detect collision using the .intersects(Rectangle)
method, and then calculate a new variable called displacementX
and displacementY
.
displacementX = Math.abs(entitiy1.getX() - entity2.getX());
displacementY = Math.abs(entitiy1.getY() - entity2.getY());
So what we have currently is the amount of pixels entity1
is intruding on entity2
(or vice versa due to the absolute value). Then, run some comparisons and move entity1
(or entity2
) by the value of the lesser displacement
, which should yield perfect-looking collision.
This is at least how I do it. The correct method for rectangular collision is to:
1) Determine if they collide
2) Correct it
3) Render
Simply preventing movement after detecting collision will look horrible (especially on low frame rates).
Hope I helped!
~Izman
Upvotes: 1
Reputation: 59283
http://docs.oracle.com/javase/6/docs/api/java/awt/Rectangle.html
Use the Rectangle
class.
http://pastebin.com/raw.php?i=TzkST3Hm
Upvotes: 3