Jump to content

Call a global user-defined function with group.callAll()


Wunderforce
 Share

Recommended Posts

Currently I have a group of sprites and I want to make them all fall at the same time.  I am trying to accomplish this with the following functions, where the group (here: fallGroup) should fall when the down arrow key is pressed. (and yes, I have already initialized keys in the create() method)

I have tried passing multiple versions of the function definition to callAll() (eg. "this.setVel", "game.setVel", ect.)  as well as several different contexts instead of 'null'  ("this", "that=this, then passing 'that' in", "game", "game.stage", ect.)  but so far nothing happens.  For some of the combos I get  "TypeError: Cannot read property 'setVel' of undefined" others produce no error but also do not call my 'setVel' function.  At this point I'm pretty lost as to what to do.

 

Edit: appleYpos, groundYpos, appleTime; are all globally defined variables

 

function setVel(sprite,vel)
{
    sprite.body.velocity.y = vel;
}

function makeFall(group)
{
     //calculate fall distance and then adjust velocity to meet time goal
    //note: velocity in physics.arcade is in pixels/sec
    let dist = appleYpos - groundYpos;
    let vel = dist/appleTime;
    group.callAll('setVel',null,vel);
}


function update()
{
   if(keys.down.isDown)
   {
      makeFall(fallGroup);
   }
}

 

Link to comment
Share on other sites

There are a few ways to do this:

// (1)

group.setAll('body.velocity.y', vel);

// (2)

group.forEach(setVel, null, null, vel);

// (3)

group.forEach(function (sprite) {
    setVel(sprite, vel);
});

// (4)

Phaser.Sprite.prototype.setVel = function (vel) {
    this.body.velocity.y = vel;
}
// […]
group.callAll('setVel', null, vel);

// (5)

function setVel(vel) {
    this.body.velocity.y = vel;
}
// […]
group.callAll(setVel, null, vel);

 

Edited by samme
fix forEach args (2); add (5)
Link to comment
Share on other sites

So callAll() won't work unless you define the function for the sprite class?

Also, I tried the forEach statement and got the following error "TypeError: callback.apply is not a function"  at Phaser.Group.forEach (phaser.js:33325).  Which looks like phaser itself might be broken.  Note this is for CE 2.10.0

Link to comment
Share on other sites

1 hour ago, Wunderforce said:

TypeError: callback.apply is not a function

That sounds like the callback itself is undefined. Double-check that the first argument is correct.

1 hour ago, Wunderforce said:

So callAll() won't work unless you define the function for the sprite class?

A method named as a string (4) must be available on the sprite (it resolves to sprite['method']).

But a method referenced directly (5) doesn't have to be.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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