Jump to content

add callback function when new game frame updates?


GxDT
 Share

Recommended Posts

Hello people of this forum.

Here is what you normally do when you wish to add a callback function for a keyboard key:

aKey = game.input.keyboard.addKey(Phaser.KeyCode.A);
aKey.onDown.add(AKeyPressed, this);

In my case I wish to add same callback function when a new game frame is updated. (Yes, I know there is a reserved update function for this stuff, but this is not how I want to use it)

Link to comment
Share on other sites

Using update function works perfectly too. I just was exploring the API and ways to work with it.

Guess I owe an explanation on what is going on.

Here I'm working on 2D platformer game  AI.

function CrabBehaviour(crabSprite) {

	this.status = {
		patrol: false,
		patrolLeft: false,
		patrolRight: false,

		attacking: false
	}

	this.leftRallyPoint = 0;
	this.rightRallyPoint = 0;

	this.patrol = function(leftPoint, rightPoint) {

		this.leftRallyPoint = leftPoint;
		this.rightRallyPoint = rightPoint;

		this.status.patrol = true;

		if (!this.status.patrolLeft && !this.status.patrolRight) {
			this.status.patrolLeft = true;
			this.patrolLeft();
		}

	}

	this.patrolRight = function () {
		this.status.patrolLeft = false;
		this.status.patrolRight = true;
		game.physics.arcade.moveToXY(evil_crab, evil_crab.body.position.x + 1, evil_crab.body.position.y, 40);
	}

	this.patrolLeft = function () {
		this.status.patrolLeft = true;
		this.status.patrolRight = false;
		game.physics.arcade.moveToXY(evil_crab, evil_crab.body.position.x - 1, evil_crab.body.position.y, 40);
	}

	this.frameEvent = function () 
	{
		if (this.status.patrol)
		{
			if (crabSprite.body.position.x <= this.leftRallyPoint  && this.status.patrolLeft) {
				this.patrolRight();
			}

			if (crabSprite.body.position.x >= this.rightRallyPoint  && this.status.patrolRight) {
				this.patrolLeft();
			}
		}
	}
}

The this.frameEvent function is responsible for tracking of what is going on 'live' so it should be called every time a new frame comes up. (In this case - change movement direction when left or right rally point is reached.

Link to comment
Share on other sites

Ah, okay, that makes sense. I do something like that in a game I'm working on, where the AI/behaviors for certain sprites come from a bunch of separate objects (StayOnPlatform, WatchesHealth, etc). They use a combination of every-frame stuff (by overriding update) and event-driven stuff (did I just get hit, did my animation complete).

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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