Reputation: 19
I am making a game in Javascript and I keep on getting this error: Enemy can be created ‣
TypeError: Cannot read property 'physics' of undefined
at new Enemy (src/prefabs/Enemy.js:7:14)
at r.<anonymous> (test/test_Enemy.js:25:22)
at c
I am not sure what is exactly wrong with the physics property. Any help would be appreciated.
Here is the code for my enemy class-
export default class Enemy extends Phaser.Sprite {
constructor(game, x, y, bulletLayer, frame) {
super(game, x, y, 'enemy', frame);
// initialize your prefab here
game.physics.enable(this, Phaser.Physics.ARCADE);
this.body.velocity.x = -175;
this.bounceTick = Math.random() * 2;
this.bulletLayer = bulletLayer;
this.outOfBoundsKill = true;
this.willFire = Phaser.Utils.chanceRoll(50);
console.log(this.willFire);
if (this.willFire) {
this.fireTimer = this.game.time.create(false);
this.fireTimer.add(3500, this.fireShot, this);
this.fireTimer.start();
}
}
fireShot() {
let bullet = this.bulletLayer.create(this.x, this.y, "enemyBullet");
this.game.physics.enable(bullet, Phaser.Physics.ARCADE);
bullet.outOfBoundsKill = true;
bullet.checkWorldBounds = true;
bullet.body.velocity.x = -250;
}
update() {
this.bounceTick += .02;
this.y += Math.sin(this.bounceTick) * 1;
}
}
Here is the code in my test enemy class-
describe("Enemy", function () {
let assert = chai.assert;
let enemy;
//Test fixture, create the same kind of enemy before each test
beforeEach(function() {
// Stubbing out the features not used in constructor
let game = sinon.stub();
game.physics = sinon.stub();
game.physics.enable = sinon.stub();
let bullets = sinon.stub();
let screen = sinon.screen();
enemy = new Enemy(game, 0, 0, bullets,screen);
});
it("can be created", function () {
let enemy = new Enemy();
assert.isOk(true);
});
Upvotes: 0
Views: 1005
Reputation: 370679
You create an Enemy here:
let enemy = new Enemy();
But as you can see in Enemy's constructor:
constructor(game, x, y, bulletLayer, frame) {
It asks for a game
argument, but you don't provide one. So game
is undefined, so game.physics
throws an error.
Upvotes: 4