Jump to content

Random enemy movement on platform using timer


specialspam
 Share

Recommended Posts

Howdy,

 

Please excuse any ignorance of this, I checked the Tanks example but I think I am after something a bit different, yet simpler:

 

I have a platform and I want to have 'enemies' moving randomly left and right. With my current code, I just have 1 enemy (the plan was to just get one working and then look at groups/objects later), it creates and starts moving using a timer but once the timer hits its first iteration the game stops and I get the following console error:

 

  1. Uncaught TypeError: Cannot read property 'apply' of undefined phaser.js:40106
  2.  

 

This is the code I have in the create function for the droid

// Create Droiddroidsprite = this.add.sprite(this.world.randomX, 450, 'droid');droidsprite.animations.add('walk');this.physics.arcade.enable(droidsprite);droidsprite.enableBody = true;droidsprite.body.bounce.y = 0.2;droidsprite.body.gravity.y = 500;droidsprite.body.collideWorldBounds = true;// Droid Movement Timer Creationgame.time.events.repeat(Phaser.Timer.SECOND * 3, 10, moveDroid(), game);

Then I have a separate function to handle the movement:

function moveDroid() {    //randomise the movement            droidmover = game.rnd.integerInRange(1, 3);    //simple if statement to choose if and which way the droid moves    if (droidmover == 1) {        droidsprite.body.velocity.x = 100;               droidsprite.animations.play('walk', 20, true);        } else if(droidmover == 2) {           droidsprite.body.velocity.x = -100;            droidsprite.animations.play('walk', 20, true);     } else {        droidsprite.body.velocity.x = 0;        droidsprite.animations.stop('walk', 20, true);    }   }

Is it the fact I am using a Sprite or maybe I should have something in the update function? I am banging my head here as I thought the timer would just simply keep going? 

 

Thanks in advance.

 

 

 

Link to comment
Share on other sites

The issue is here:

game.time.events.repeat(Phaser.Timer.SECOND * 3, 10, moveDroid(), game);

You need to pass 'moveDroid' and not 'moveDroid()' which will cause the function to be executed immediately within this line, but not by the timer, which is being passed the result of calling moveDroid (undefined in this case as the function does not return anything) rather than the function itself.

game.time.events.repeat(Phaser.Timer.SECOND * 3, 10, moveDroid, game);
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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