Jump to content

Sprite.Body is undefined


piotr
 Share

Recommended Posts

Hi all,

Why am I getting the error "Cannot read property 'velocity' of undefined" when calling the stopMoving function in Ball?

Thanks

 

var Ball = function (game) {
  Phaser.Sprite.call(this, game,0,0,'ball');
  game.physics.enable(this, Phaser.Physics.ARCADE);
  this.anchor.setTo(0.5, 0.5);
  this.scale.setTo(1);
};

Ball.prototype = Object.create(Phaser.Sprite.prototype);
Ball.prototype.constructor = Ball;

Ball.prototype.stopMoving = function() {
      this.body.velocity.setTo(0, 0);
};

Ball.prototype.moveTo = function(start, destination) {
	game.world.add(this); //detach from parent
 	this.reset(start.x, start.y); 
    this.game.physics.arcade.moveToXY(this, destination.x, destination.y, 500);

};

playstate

var playState = {
	
	create: function() {
		this.createThrower();
		this.createCatcher();
		this.createBall();
	},

	update: function() {
		game.physics.arcade.overlap(this.ball, this.player2, this.ball.stopMoving, null, this);
	},

	createThrower: function() {	
		this.playerGroup = game.add.group();
		this.player = new Player(this.game);
		this.game.add.existing(this.player);
		this.playerGroup.add(this.player);
	},

	createCatcher: function() {	
		this.player2 = new Player(this.game);
		this.game.add.existing(this.player2);
		this.playerGroup.add(this.player2);
	},

	castSpell: function(sprite) {
		this.ball.moveTo(this.player, this.player2);
	},

	createBall: function() {
		this.ball = new Ball(this.game);
		this.player.addChild(this.ball);
	},
};

 

Link to comment
Share on other sites

Try putting a breakpoint in the stop moving function and see what 'this' actually is...

I have a suspicion that it won't be the ball object that you think it is, but the playstate object instead...

The last argument sent to the overlap function is the callback context, meaning the object that "this" points to inside the callback function...

There are several things you can do here:
- Change the callback context to be the ball you are testing against.
- Move the callback function to the playstate object, and use this.ball.body.velocity instead.

Or, the one I would recommend,

- Change the callback function to one on the playstate object, and make use of the parameters sent to the callback function... From the docs:

An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter.

update: function()
    {
        game.physics.arcade.overlap(this.ball, this.player2, this.collisionCallback, null, this);
    },

playstate = {
    // Your code
    collisionCallback: function(ball, player)
    {
        ball.stopMoving();
    }
}

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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