Jump to content

Near-identical code behaves differently in different states


DoubleW
 Share

Recommended Posts

I am testing whether I can have two states move back and forth while properly updating some shared variables (it's a game with randomized content, so it's important that I can run create() each time).

I have the state switch bound to separate keys and the update function of each state polls them, once key in each state. However, in the menu state, the transition works fine but in the Level state it causes a crash. All of the global test variables increment the way they are supposed to, so that's fine. The code behaves the same if I use signal events instead of the update function, so I am misunderstanding something about state transitions. What is it?

 

/**
 * Menu state.
 */
function Menu() {
	Phaser.State.call(this);
}

/** @type Phaser.State */
var proto = Object.create(Phaser.State);
Menu.prototype = proto;

Menu.prototype.preload = function() {
	
};

Menu.prototype.create = function() {
	this.pressKey = this.game.input.keyboard.addKey(Phaser.Keyboard.A);
	var sprite = this.add.sprite(this.world.centerX, this.world.centerY, "tap-to-start");
	sprite.anchor.set(0.5, 0.5);
	//this.input.onDown.add(this.startGame, this);
	//this.pressKey.onDown.addOnce(this.startGame, this);
};

Menu.prototype.update = function(){
	if(this.pressKey.isDown){
		this.startGame();
	}
};

Menu.prototype.render = function(){
	this.game.debug.text(testvar, 100, 118);
	this.game.debug.text(testobj.testvar2++, 100, 128);
	this.game.debug.text(testobj.prot.testvar3, 100, 138);
	this.game.debug.text(state1++, 100, 148);
	//this.game.debug.text(state2, 100, 158);
	//this.game.debug.text(state3, 100, 168);
};

Menu.prototype.startGame = function() {
	this.game.state.start("Level");
};

 

/**
 * Level state.
 */
function Level() {
	Phaser.State.call(this);
}

/** @type Phaser.State */
var proto = Object.create(Phaser.State);
Level.prototype = proto;

Level.prototype.init = function() {
	
};

Level.prototype.create = function() {
	this.aKey = this.game.input.keyboard.addKey(Phaser.Keyboard.X);
	//this.aKey.onDown.addOnce(this.quitGame, this);
};

Level.prototype.update = function() {
	state1 +=1;
	if(this.aKey.isDown){
		this.quitGame();
	}
};

Level.prototype.render = function() {
	this.game.debug.text(testvar, 100, 118);
	this.game.debug.text(testobj.testvar2, 100, 128);
	this.game.debug.text(testobj.prot.testvar3, 100, 138);
	this.game.debug.text(state1, 100, 148);
	this.game.debug.text(state2, 100, 158);
	this.game.debug.text(state3, 100, 168);
};

Level.prototype.quitGame = function() {
	testvar1 +=1;
	this.game.state.start("Menu");
};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...