Gravity stops when side-collision detected
Posted
by
Adrian Marszalek
on Game Development
See other posts from Game Development
or by Adrian Marszalek
Published on 2012-08-27T18:36:00Z
Indexed on
2012/08/27
21:57 UTC
Read the original article
Hit count: 583
java
|collision-detection
Please, look at this GIF:
The label on the animation says "Move button is pressed, then released". And you can see when it's pressed (and player's getCenterY() is above wall getCenterY()), gravity doesn't work. I'm trying to fix it since yesterday, but I can't. All methods are called from game loop.
public void move() {
if (left) {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)
game.lvl1.getX()[i] += game.physic.xVel;
break;
}
} else if (right) {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)
game.lvl1.getX()[i] -= game.physic.xVel;
break;
}
}
}
int manCenterX, manCenterY, boxCenterX, boxCenterY;
//gravity stop
public void checkCollision() {
for (int i = 0; i < game.lvl1.getX().length; i++) {
manCenterX = (int) game.man.getBounds().getCenterX();
manCenterY = (int) game.man.getBounds().getCenterY();
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
boxCenterX = (int) game.lvl1.getBounds(i).getCenterX();
boxCenterY = (int) game.lvl1.getBounds(i).getCenterY();
if (manCenterY - boxCenterY > 0 || manCenterY - boxCenterY < 0) {
game.man.setyPos(-2f);
game.man.isFalling = false;
}
}
}
}
//left side of walls
public void colliLeft() {
for (int i = 0; i < game.lvl1.getX().length; i++) {
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
if (manCenterX - boxCenterX < 0) {
for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {
game.lvl1.getX()[i1] += game.physic.xVel;
game.man.isFalling = true;
}
}
}
}
}
//right side of walls
public void colliRight() {
for (int i = 0; i < game.lvl1.getX().length; i++) {
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
if (manCenterX - boxCenterX > 0) {
for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {
game.lvl1.getX()[i1] += -game.physic.xVel;
game.man.isFalling = true;
}
}
}
}
}
public void gravity() {
game.man.setyPos(yVel);
}
//not called from gameloop: public void setyPos(float yPos) {
this.yPos += yPos;
}
© Game Development or respective owner