Sprite.Body is undefined

Recommended Posts

Hi all,

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



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);

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);



var playState = {
	create: function() {

	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);

	createCatcher: function() {	
		this.player2 = new Player(this.game);

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

	createBall: function() {
		this.ball = new Ball(this.game);


Share this post

Link to post
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)

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.