There is a problem with my code when I enter and play again. The game works properly, but for some reason, when I lose the game, a game over appears, and when I enter it and return to the main scene, the game doesn’t work properly.
It looks like you’re defining some of your game variables in the global scope:
Because of this, those variables only get set when the script is loaded by the browser into RAM, not necessarily when you reload the scene. That means that when you reload the scene, lives is still at 0. Consider moving them into the initialize function and calling them with this
Something like:
CharacterMovement.prototype.initialize = function() {
this.entity.collision.on('collisionstart', this.onCollisionStart, this);
var score = this.app.root.findByName("KeyDisplay");
score.element.text = key_Counter.toString();
var invisible= this.app.root.findByName("InvisibilityDisplay");
invisible.element.text = invisible_Counter.toString();
var life = this.app.root.findByName("LifeDisplay");
life.element.text = lives.toString();
this.key_Counter = 0;
this.bumps = 0;
this.lives = 3;
this.invisible_Counter = 0;
};
And then calling them the same way in your collision logic:
CharacterMovement.prototype.onCollisionStart = function(result) {
...
if (this.lives == 0) {
var SceneToOpen = this.app.getSceneUrl("GameOver");
this.app.scenes.loadScene(SceneToOpen);
var CurrentScene = this.app.root.findByName("Root");
CurrentScene.destroy();
}
...
Right. You moved invisible counter out of the global scope, so invisible_Counter by itself will return undefined. If you are calling it from Character movement, it will have to be this.invisible_Counter
Is the error you’re getting coming from Character Movement.