I need to make it so that when sprites that I have created collide with each (I have already figured out the collision) other they teleport to the last x and y position they were on before they collided so that they don't go through each other. I have tried to use this code.
double x, y, x2, y2;
if(!r1.intersects(r2)){
x = z.getX();
y = z.getY();
x2 = z2.getX();
y2 = z2.getY();
}
if(r1.intersects(r2)){
z.setX(x);
z.setY(y);
z2.setX(x2);
z2.setY(y2);
}
But it doesn't work because all the sprites is inside each other. I have also tried to use this.
if(r1.intersects(r2)){
z.setX(z.getX() - 1);
z.setY(z.getY() - 1);
z2.setX(z2.getX() + 1);
z2.setY(z2.getY() + 1);
}
That code makes it so that the sprites can't go through each other but it will make it so that the first sprites that spawn becomes alot faster than the later ones because in the beginning it's more sprites that collide with each other.
I assume these sprites are more complex than simple circles? I am also assuming that you have implemented some "bounding box" collision detection.
If that's the case then I would calculate a vector after the collision is detected. The vector would be a magnitude of how much each sprite has intersected each other by, relative to their center points. You can then move each sprite in opposite directions along the vector, scaling by how far they have intersected. This would position each sprite so they are just touching.
This is a nice solution because if each sprite is moving at more than 1 pixel per frame, the last positions of each sprite could be a 10's of pixels away. It would never look like they actually collided.
..This would work for both complex sprites and simple circles.