Right collision

So basically I'm trying to figure out how to make the right collision between two rectangles. Detection is not a problem, but the rectangles begin to pinch. I wanted to reset the position, but how to do it. I am trying to use dx and dy to reset, but will not reset in the correct coordinates.

http://i.stack.imgur.com/IU6sK.png (Sorry for not using 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 showing how I'm trying to use it for the top. (this = white rectangle and e = orange) I used my Entity class, which extends the Rectangle.

I check the intersection before calling. This is a function in the white object, and the intersection is checked in the main loop update function.

If I use this, there is 1px between the rectangles. Any ideas? Thanks for any help :)

+4
source share
2 answers

The best way to make a rectangular collision is to use the Rectangle class to detect a collision using the .intersects(Rectangle) method, and then compute a new variable called displacementX and displacementY .

displacementX = Math.abs(entitiy1.getX() - entity2.getX());

displacementY = Math.abs(entitiy1.getY() - entity2.getY());

So, currently the number of pixels of entity1 superimposed on entity2 (or vice versa due to the absolute value). Then do some comparisons and move entity1 (or entity2 ) to a value of less displacement , which should provide a perfect collision.

This is at least how I do it. The correct method for a rectangular collision:

1) Determine if they encountered

2) fix it

3) Render

Simply preventing movement after collision detection will look awful (especially at low frame rates).

I hope I helped!

~ Izman

+1
source

Source: https://habr.com/ru/post/1444115/


All Articles