for my game I have coded a basic life system and once the collision with the sprite is done I destroy it but it continues to work even after being destroyed how to fix it?
My code :
//condition for wins the health points
if (character.x < life.x + life.width + 33 && character.x + character.width - 33
life.x && healthPoints !==3 )
{
healthPoints++;
//Once time the sprite enter in collision this one is deleted of the memory
life.destroy();
}
//reset character and the bridge after the fall and lose of HP
if (character.y < wall.y + wall.height && character.y + character.height > wall.y
&& healthPoints !==0)
{
LoseHP()
platform2Reached = false
platform3Reached = false
/*healthPoints--;
bridge.rotated = false;*/
character.body.pos.x = 38;
character.body.pos.y = 505;
bridge.syncGameObject()/*.setDisplaySize(1,10)*/.setBodyScale(1);
bridge.body.pos.x = 95;
bridge.body.pos.y = 528;
bodyBlock.body.pos.x = 91;
bodyBlock.body.pos.y = 520;
}
//condition for wins the health points
if (character.x < life.x + life.width + 33 && character.x + character.width - 33
> life.x && healthPoints !==3 )
{
healthPoints++;
//Once time the sprite enter in collision this one is deleted of the memory
life.destroy();
}
//Condition of defeat
if (healthPoints == 0)
{
text.setText('YOU\nLOSE');
text.setPosition(text.width-20,text.height+150 );
tripleFace.anims.play('left');
character.setVelocity(0);
character.anims.play('stop');
}
Hello. It is difficult to say what can be wrong in your code, even with the code you posted in your last message… Like “tac” has said, maybe you have a logical error?
Are you sure your collision detection is working? Is your incrementation “healthPoints++” working?
Have you tried to debug your collision by sending a message to the javascript console?
If the collision is right… I do not know what else to say …
Maybe you can test the “active” property of your “life” object to check if “life” has been deactivated correctly after destroy().
life.destroy();
if(life.active == true){
console.log(“Error → life is allways active after destroy()”);
}
else{
console.log(“OK → life has been destroyed!”);
}
If i don’t have correctly understood your problem and the collision is working even if the life has been destroyed, maybe you need to delete life OR set your life variable to “null” or “false”?
life.destroy();
life = false; // ← Replace your object by FALSE
if(life !== false){//If life IS NOT FALSE
if (character.x < life.x + life.width + 33 && character.x + character.width - 33 > life.x && healthPoints !==3 )
{
console.log(“Collision is working!”);
life.destroy();
life = false; // ← Life is now FALSE
}
}
Yes it’s fine it works now I don’t get my life back once my heart is destroyed and when I go back to the position it is in.
I just had to make a slight modification my life.destroy() must always be before the 1st life = false otherwise I have an error and I must have only one destroy().