Jump to content

Moving snake forward without event


Milo
 Share

Recommended Posts

Hello,

I'm trying to code the curve fever game with phaser. I just started (and I am a newbie at Phaser) and I have a few problems:

- How do I limit the world borders?

- I want the snake to move forward continuously forward, without any input ( I did this with a loop as you can see in the create() function). But when I press the arrows to turn, the velocity increases. I can modify the loop timing (in Create() )to match the velocity but I think that there are better solutions and i prefer to make the turning slower rather than making the forward loop faster, so that's why I ask it here :)

const numSnakeSections = 30;
const snakeSpacer = 1;

let snakeHead;
let snakeSection = new Array(30).fill('');
let snakePath = new Array(numSnakeSections * snakeSpacer).fill('');

const preload = function () {
  game.load.image('ball', 'assets/sprites/ball.png');
};

const SnakeDot = function() {
  const section = game.add.sprite(400, 300, 'ball');
  section.scale.setTo(0.03, 0.03);
  section.anchor.setTo(0.5, 0.5);
  return section;
};

const initSnakeSection = function() {
  snakeSection = snakeSection.map(x => SnakeDot());
};

const initSnakePath = function() {
  snakePath = snakePath.map(x => new Phaser.Point(400, 300));
};

const create = function() {
  game.physics.startSystem(Phaser.Physics.ARCADE);
  game.world.setBounds(0, 0, 800, 600);

  cursors = game.input.keyboard.createCursorKeys();
  snakeHead = SnakeDot();

  game.physics.enable(snakeHead, Phaser.Physics.ARCADE);
  game.time.events.loop(Phaser.Timer.SECOND / 33, updateSnake, this);

  initSnakeSection();
  initSnakePath();
};

const updateSnakePath = function () {
  const part = snakePath.pop();
  part.setTo(snakeHead.x, snakeHead.y);
  snakePath.unshift(part);
};

const moveSnake = function(angularVelocity) {
  snakeHead.body.angularVelocity = angularVelocity;
  snakeHead.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(snakeHead.angle, 300));

  updateSnakePath();

  snakeSection.forEach((position, index) => {
    position.x = snakePath[index].x;
    position.y = snakePath[index].y;
  });

};

const updateSnake = function() {
  snakeHead.body.velocity.setTo(0, 0);
  moveSnake(0);
};

const handleLeft = function() {
  moveSnake(-300);
};

const handleRight = function() {
  moveSnake(300);
};

const update = function() {
  snakeHead.body.velocity.setTo(0, 0);
  snakeHead.body.angularVelocity = 0;

  if (cursors.left.isDown) handleLeft()
  else if (cursors.right.isDown) handleRight();
};

const render = function() {
  game.debug.spriteInfo(snakeHead, 32, 32);
};

const options = {
  preload,
  create,
  update,
  render
};

const game = new Phaser.Game(800, 600, Phaser.CANVAS, 'CurveFever', options);

Thanks! 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...