Does anyone have an example of creating a sprite and physics object in one single class?
edited, removed the code as I broke it when removing stuff to keep it simple! see Character class instead
Ok so how do I attach a body to my sprite? I want the body and sprite in the SAME class as one single object
class Player extends Phaser.Physics.Arcade.Sprite{
constructor(scene, x, y, texture_atlas, texture){
super(scene, x, y, texture_atlas, texture);
scene.add.existing(this);
}move_left(){
body.setVelocityX(-100);
}move_right(){
body.setVelocityX(100);
}jump(){
}
}
if I do
var guy = new Player(blah blah blah);
console.log(guy);
console.log(guy.body);
the body is null for both console log entries
Ok now I have this
class Player extends Phaser.Physics.Arcade.Sprite{
constructor(scene, x, y, texture_atlas, texture){
super(scene, x, y, texture_atlas, texture);
var custom_body = new Phaser.Physics.Arcade.Body(scene.physics.world, this);
this.body = custom_body;
scene.add.existing(this);
}
move_right(){
this.setVelocityX(400);
//this.x += 5;
//this.body.x = 500;
console.log("after telling body to move");
}
}
but when I call it in update() like so, nothing happens
update(time, delta){
var cursors = this.input.keyboard.createCursorKeys();
if(cursors.left.isDown){
console.log("left is down");
this.player.setVelocityX(400);
}
if(cursors.right.isDown){
console.log("right is down");
this.player.move_right();
}
}
My scene is set up like so with the player variable in the constructor so it can be accessed in the update()
class Level_1 extends Phaser.Scene{
constructor(){
super(“level_one”);
this.player;
}
the player doesn’t move at all. If I do player.x = 400 in the move_right() function, it will instantly move, but I need it to slowly move in that direction.
I don’t get Phaser, because I had this exact code set up in one big file and it ran fine. Now that I broke it out into classes, it fails.
Did you try stepping through the code?
I ended up adding this
this.scene.physics.world.enableBody(this, 0);
to my Constructor and that seemed to work for registering my Sprite as a Body