felluminati / PhaserWorkshop

Fullstack mini stackathon
1 stars 8 forks source link

Myserious error on "Making the Ground" #18

Open fterdal opened 5 years ago

fterdal commented 5 years ago

I get Uncaught TypeError: Cannot read property 'add' of undefined when I try to add the ground to the FgScene. Screenshot and code below:

FgScene.js

/* global Phaser */
import Player from '../entity/Player';
import Ground from '../entity/Ground';

export default class FgScene extends Phaser.Scene {
  constructor() {
    super('FgScene');
  }

  preload() {
    // Sprites
    this.load.image('ground', 'assets/sprites/ground.png');
    this.load.spritesheet('josh', 'assets/spriteSheets/josh.png', {
      frameWidth: 340,
      frameHeight: 460,
    });

  }

  create() {
    // Create the ground and lasers
    this.createGroups();

    // Josh. The player. Our sprite is a little large, so we'll scale it down
    this.player = new Player(this, 20, 400, 'josh').setScale(0.25);

  }

  // Make the ground
  createGround(x, y) {
    this.groundGroup.create(x, y, 'ground');
  }

  // Make all the groups
  createGroups() {
    this.groundGroup = this.physics.add.staticGroup({ classType: Ground });
    //add ground to group
    this.createGround(160, 540);
    this.createGround(600, 540);
  }

}

Ground.js

/* global Phaser */
import 'phaser';

export default class Ground extends Phaser.Physics.Arcade.Sprite {
  constructor(scene, x, y, spriteKey) {
    super(scene, x, y, spriteKey);

    // << INITIALIZE PLAYER ATTRIBUTES HERE >>
    this.scene = scene;
    // Add ground to scene and enable physics
    this.scene.physics.world.enable(this);
    this.scene.add.existing(this);
  }

  create() {
    this.groundGroup = this.physics.add.staticGroup({ classType: Ground });
  }

}
screen shot 2018-12-13 at 4 35 30 pm
fterdal commented 5 years ago

Ah, I think I figured it out. We need the students to add the changes to config/config.js about the physics. E.g.

physics: {    // Optional: specify physics engine and configuration
    default: 'arcade',  // A simple and performant physics engine
    arcade: {
      gravity: { y: 1500 },  // Game objects will by default be affected by gravity
      debug: false,
    },
},

Otherwise, they can't use this.physics.add, because the physics object hasn't been initialized yet.