Jump to content

issey
 Share

Recommended Posts

Hi everyone!

I need a little help with understanding how to properly set timer functions. I'm new to javascript so I often run into syntax issues.

I have a group ("starGroup") containing 10 "star" objects. When a user clicks on one of the group's "star" object, I'm hoping to have it tween before being destroyed.
Everything seems to work properly up to the end of the tween, however I am having issues setting star.destroy until after the tween.
I read in another post that we could use Phaser's timer for this instance, however my timer functions don't seem to be working. I get a return of: "Uncaught TypeError: Cannot read property 'destroy' of undefined(…)".

A little help needed?

Many thanks!

Here's the code:

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
    
  game.load.image('star', 'assets/images/star.png');
}

function create() {
  
  //Create random Star group
  starGroup = game.add.group();
  //  And add 10 sprites to it
  for (var i = 0; i < 10; i++)
  {starGroup.create(game.world.randomX, game.world.randomY, 'star');}
  //  Make them all input enabled
  starGroup.setAll('inputEnabled', true);
  starGroup.setAll('input.useHandCursor', true);
  // Call all in group
  starGroup.callAll('events.onInputDown.add', 'events.onInputDown', starClick); 
}

function starClick (star) {

  starRemoveTweenA = game.add.tween(star.scale).to( { x:2, y:2 }, 800, "Elastic.easeOut");
  starRemoveTweenB = game.add.tween(star.scale).to( { x:0, y:0 }, 800, "Elastic");
  starRemoveTweenA.chain(starRemoveTweenB);
  starRemoveTweenA.start();

  //star.destroy(); //Hiding this to set a timer instead

  //Setting a timer
  game.time.events.add(2000, functionDestroy, this);
}


function functionDestroy (star) {
  star.destroy(); // This is where the console is reporting an issue
}


function update() {}

 

Link to comment
Share on other sites

Hi issey, your timer is working correctly but `star` is missing from the callback. The error comes because it's trying to do

function functionDestroy (undefined) {
  (undefined).destroy(); // → Uncaught TypeError: Cannot read property 'destroy' of undefined
}

You can use

game.time.events.add(2000, functionDestroy, this, star);

Any "extra" arguments are forwarded along to the callback.

You could also use instead

game.time.events.add(2000, star.destroy, star);

(and remove `functionDestroy`).

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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