config.js
var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
physics: {
default: "arcade",
arcade: {
gravity: { y: 200 },
},
},
scene: [EvoGame],
};
var game = new Phaser.Game(config);
evogame.js
class EvoGame extends Phaser.Scene {
constructor() {
super("EvoGame");
}
preload() {
this.load.image("Squittle", "assets/squittle.png");
}
create() {
let player = this.physics.add.image(400, 300, "Squittle");
player.setBounce(0.2);
player.setCollideWorldBounds(true);
this.input.keyboard.on(
"keydown-D",
function (player) {
this.image.setVelocityX += 10;
},
this
);
}
update() {}
}
When I try to move the image using the D key, I get the error
Uncaught TypeError: Cannot read property 'setVelocityX' of undefined
at EvoGame.<anonymous> (evogame.js:18)
at KeyboardPlugin.emit (phaser.js:1906)
at KeyboardPlugin.update (phaser.js:185828)
at EventEmitter.emit (phaser.js:1905)
at onKeyDown (phaser.js:92223)
I have the player defined in create() and if I do it without let, var, or const, it doesn't render the player image at all. I'm building the game using Phaser, and besides that it is just plain html, css, and javascript.
When I console.log the player in the create() function, it shows an object with x = 400 which is where i have it initially set. I tried to access it with this.player.x but it still shows it undefined.
question from:
https://stackoverflow.com/questions/65858502/phaser-throws-error-as-player-being-undefined-during-key-event 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…