I am having lots of problems with the collidesWith() method on AndEngine. I can see that on the screen, the player and coin sprites I have created are obviously colliding, yet the code below is not executing.
scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() {
// TODO Auto-generated method stub
}
@Override
public void onUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
checkCollision();
scoreText.setText(String.valueOf(score));
}
});
return scene;
}
public void checkCollision() {
if(player1.collidesWith(coin)) {
player1.setColor(Color.RED);
coin.detachSelf();
score+=200;
}
}
public void loadSprites() { //This loads the sprites
coin = new Coin(210, 220, this.coinTR,
this.getVertexBufferObjectManager());
player1 = new Player(INITX, INITY, this.player,
this.getVertexBufferObjectManager()) {
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
super.onManagedUpdate(pSecondsElapsed);
// this.runRight();
if (this.jump) {
this.jump();
this.checkPositionForJump();
}
}
};
}
public void jump() { //This jump method is part of the player class, it just follows a parabolic path to jump
this.mX+=SPEED;
this.mY = (float) (((this.mX - (this.startX + this.VERTX)) * (this.mX - (this.startX + this.VERTX)))
/ (this.STRETCH) + this.startY + this.VERTY);
}
As you can see it just follows a parabolic path from wherever it is currently positioned.
In the checkCollision() method, the if statement never evaluates to true. I have tried every single method I know and cannot get it to work properly. The only time it pseudo works is when I set the sprites to be in the exact same initial position, but other than that it never works. Any help would be greatly appreciated!
Modifying a sprite
's location by setting its' mX
and/or mY
members can lead to the problems you're experiencing. It's always a good idea to use the setters for this.
Change the jump
method (and any other place) so it uses setX
and setY
methods instead of mX
and mY
, and it should solve your problem.