I am trying to make the Snake game and the actual position of the snake is always behind by one.
this is my full code:
import 'phaser';
import { DOWN, LEFT, RIGHT, UP } from 'phaser';
export default class SnakeGame extends Phaser.Scene {
constructor() {
super('SnakeGame');
this.DIRECTION = RIGHT
this.step = 16
}
preload() {
this.load.setBaseURL('http://labs.phaser.io')
this.load.image("food", "assets/games/snake/food.png")
this.load.image("body_part", "assets/games/snake/body.png")
}
create() {
this.food = this.physics.add.sprite(Phaser.Math.Between(1, config.width / this.step - 1) * this.step, Phaser.Math.Between(1, config.height / this.step - 1) * this.step, "food")
this.tail = new Phaser.Geom.Point(16, 16)
this.snake_head = this.physics.add.sprite(config.width / 2, config.height / 2, "body_part")
this.snake_body = this.physics.add.group()
this.cursors = this.input.keyboard.createCursorKeys();
this.physics.add.collider(this.snake_head, this.food, this.collectFood, null, this)
this.physics.add.collider(this.snake_head, this.snake_body, this.eatSelf, null, this)
}
update() {
if (this.cursors.left.isDown && this.DIRECTION !== RIGHT) {
this.DIRECTION = LEFT
} else if (this.cursors.right.isDown && this.DIRECTION !== LEFT) {
this.DIRECTION = RIGHT
} else if (this.cursors.up.isDown && this.DIRECTION !== DOWN) {
this.DIRECTION = UP
} else if (this.cursors.down.isDown && this.DIRECTION !== UP) {
this.DIRECTION = DOWN
}
if (this.DIRECTION === UP) this.snake_head.setY(Phaser.Math.Wrap(this.snake_head.y - this.step, 0, config.height))
else if (this.DIRECTION === DOWN) this.snake_head.setY(Phaser.Math.Wrap(this.snake_head.y + this.step, 0, config.height))
else if (this.DIRECTION === LEFT) this.snake_head.setX(Phaser.Math.Wrap(this.snake_head.x - this.step, 0, config.width))
else if (this.DIRECTION === RIGHT) this.snake_head.setX(Phaser.Math.Wrap(this.snake_head.x + this.step, 0, config.width))
if (this.snake_body.countActive(true) !== 0) {
Phaser.Actions.ShiftPosition(this.snake_body.getChildren(), this.snake_head.x, this.snake_head.y, this.DIRECTION, this.tail)
}
}
collectFood(snake_head, food) {
food.disableBody(true, true)
food.enableBody(true, Phaser.Math.Between(0, config.width), Phaser.Math.Between(0, config.height), true, true)
this.snake_body.create(-100, -100, "body_part")
}
eatSelf(snake_head, snake_body) {
this.scene.pause();
console.log("GAME OVER");
this.gameOver = true;
}
}
const config = {
type: Phaser.AUTO,
backgroundColor: '#50f',
width: 2 ** 10,
height: 2 ** 9,
physics: {
default: 'arcade',
arcade: {
debug: true,
},
},
fps: {
target: 10,
forceSetTimeOut: true
},
scene: SnakeGame
};
const game = new Phaser.Game(config);