So, as per your suggestions, I’ve made some changes to the collision detection code. Largely it works much better, so thank you all for your help in that aspect - but I’ve got one more question. The action of an entity snapping to the respective edges of the entity that it’s colliding with, it shows a visible snapping effect, as if the entity still goes too far before being pushed ‘back’. Does anyone have any suggestions on how to prevent this? It’s what I was trying to achieve with my old solution.
Updated code:
public void doCollisionsForEntity(BaseEntity b) {
calcIndexSet(b.x, b.y, b.width, b.height);
testedWith.clear();
for (int x = iSet.eOX; x <= iSet.eEX; x++) {
if (x < 0) {
continue;
}
for (int y = iSet.eOY; y <= iSet.eEY; y++) {
if (y < 0) {
continue;
}
//System.out.println("x: " + x + ", y: " + y);
if (grid[x][y].inUse) {
for (BaseEntity bEnt : grid[x][y].entlist) {
if (bEnt != b && !testedWith.contains(bEnt)) {
if (bEnt.x + bEnt.width <= b.x || b.x + b.width + b._xvel<= bEnt.x) {
continue;
}
if (bEnt.y + bEnt.height <= b.y || b.y + b.height + b._yvel <= bEnt.y) {
continue;
}
testedWith.add(bEnt);
//System.out.println("Testing " + b.targetName + " with: " + bEnt.targetName);
int distanceR = (bEnt.x - (b.x + b.width));
int distanceL = (b.x - (bEnt.x + bEnt.width));
int distanceB = (bEnt.y - (b.y + b.height));
int distanceT = (b.y - (bEnt.y + bEnt.height));
//System.out.println(b.targetName + "&" + bEnt.targetName + " - l dist: " + distanceL + ", r dist: " + distanceR + ", t dist: " + distanceT + ", b dist: " + distanceB);
boolean collidingR = ((distanceR <= 0) && bEnt.x > b.x);
boolean collidingL = ((distanceL <= 0) && bEnt.x < b.x);
boolean collidingB = ((distanceB <= 0) && bEnt.y > b.y);
boolean collidingT = ((distanceT <= 0) && bEnt.y < b.y);
//System.out.println(b.targetName + "&" + bEnt.targetName + " - cl: " + _cL + ", cR: " + _cR + ", cB: " + _cB + ", cT: " + _cT);
if (collidingR && b._xvel > 0) {
b.x = bEnt.x - b.width;
b._xvel = 0;
}
if (collidingL && b._xvel < 0) {
b.x = bEnt.x + bEnt.width;
b._xvel = 0;
}
if (collidingT && b._yvel < 0) {
b.y = bEnt.y + bEnt.height;
b._yvel = 0;
}
if (collidingB && b._yvel > 0) {
b.y = bEnt.y - b.height;
b._yvel = 0;
}
}
}
}
}
}
}
This is the code in my EntityManager class that actually handles the updating of positions, and the order in which the chain of logic is executed is as follows:
public void updateEntities() {
if (entGrid == null) {
return;
}
for (BaseEntity b : entityTree) {
if (!b.dormant) {
if (MapManager.onScreen(b.x, b.y, b.width, b.health) || b.neverIgnore) {
if (b.doesCollide) {
entGrid.doCollisionsForEntity(b);
//save TIME updating positions and grid indices!
if (b._xvel != 0 || b._yvel != 0) {
entGrid.removeEntity(b);
b.x += b._xvel;
b.y += b._yvel;
entGrid.addEntity(b);
}
}
}
}
}
}
So my question is: is there a way to prevent the visible snapping effects that this code produces?
Thank you for your help.