Search code examples
javascriptspritegame-physics

How to reset its position back to the origin when it reach the end of frame? javascript


var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create});

function preload() {

  //  You can fill the preloader with as many assets as your game requires

  //  Here we are loading an image. The first parameter is the unique
  //  string by which we'll identify the image later in our code.

  //  The second parameter is the URL of the image (relative)
}

function create() {

  //  This creates a simple sprite that is using our loaded image and
  //  displays it on-screen
  //  and assign it to a variable

  var image = game.add.sprite(0, 0, 'einstein');
  game.physics.enable(image, Phaser.Physics.ARCADE);
  image.body.velocity.x=150;

  //my attempt below
  if(image.body.coordinate.x > 1){
    var image = game.add.sprite(0, 0, 'einstein');
  }
}

I am currently trying to get reset the image sprite back to coordinates 0,0 when it leaves completely off the screen so basically once it its off the canvas it will reset back and have been at it for a few hours tried many things Any tips would be appreciated. As I been trying to actively get the coordinates so that it is aware when to load the image when the first one is gone.

Thanks


Solution

  • I think that the create() method only gets called when you create it. This way the if statement only gets called once. You need to check it multiple times (eg each frame).

    it appears Phase has a class that checks if you're out of bounds. (onOutOfBounds) try:

      function create() {
    
      //  This creates a simple sprite that is using our loaded image and
      //  displays it on-screen
      //  and assign it to a variable
    
      var image = game.add.sprite(0, 0, 'einstein');
      game.physics.enable(image, Phaser.Physics.ARCADE);
      image.body.velocity.x=150;
    
      image.checkWorldBounds= true;
      image.events.onOutOfBounds.add(resetimage, this);
    
      }
      function resetimage(image) {
    
        image.reset(image.x, image.y);
      }
    

    Edit: previous example doesnt apply on sprites. use onOutOfBounds instead.

    Edit: link to a working example: Phaser out of bounds