Jump to content

The proper way to add physics to an animation called from a sprite sheet


blackhawx
 Share

Recommended Posts

I successfully have my plane showing and animating within my game. It's even drag-gable, and has cursor event handling attached to it.  But I would like it to also have physics for collision purposes.  But whenever I attempt to do so, the browser complains.  Here is the code that works:

 

function init() {

  this.gameW = this.sys.game.config.width;
  this.gameH = this.sys.game.config.height;
  this.playerSpeed = 8;

}

function preload() {

  this.load.atlas('sheet', 'game02/media/sheet.png', 'game02/media/sheet.json');
}

function create() {

  //INITIATE KEYBOARD CONTROLLERS FOR SCENE
  this.cursors = this.input.keyboard.createCursorKeys();

  //SCENERY SPRITES CALLED FROM MY 'SHEET' SPRITE SHEET
  this.bg = this.add.tileSprite(0, 0, 800, 480, 'sheet', 'background.png').setOrigin(0);
  this.mountain = this.add.tileSprite(0, this.gameH / 1.2, 800, 100, 'sheet', 'mountain.png').setOrigin(0);

  //ANIMATE SPRITE
  this.anims.create({
    key: 'plane',
    repeat: -1,
    frameRate: 27,
    frames: this.anims.generateFrameNames('sheet', {
      start: 1,
      end: 3,
      prefix: 'planeBlue',
      suffix: '.png'
    })
  });

  //ADD ANIMATION SPRITE TO STAGE AND PLAY IT
  this.plane = this.add.sprite(this.gameW / 2, this.gameH / 2, 'sheet').play('plane');

  //SET HAND CURSOR OVER PLANE
  this.plane.setInteractive({
    useHandCursor: true
  });

  //SET PLANE TO BE INTERACTIVE (FOR MOUSE USAGE)
  this.plane.setInteractive();

  //SET PLANE TO BE DRAGGABLE (FPR MOUSE USAGE)
  this.input.setDraggable(this.plane);

  //EVENT HANDLING FOR DRAG-GABLE OBJECTS
  this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
    gameObject.x = dragX;
    gameObject.y = dragY;
  });

}

 

...But the moment I try to add physics to this.plane... 

 this.physics.add.existing(this.plane);

 

...I get a message in my console that says...

Quote

Cannot read property 'add' of undefined

How can I improve upon this?

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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