Jump to content

Snake Game


belliott554
 Share

Recommended Posts

I am making a game using the phaser game engine similar to the popular game snake. I am looking for code to that if the right arrow key is pressed once, the snake continues right until another key is pressed or it hits the wall. I am wondering if anybody knows how to do this using the current phaser engine or if it could be added in the future. thanks 

Link to comment
Share on other sites

you can set the body's x and y velocity to equal to variables then change those variables on keypress, eg :

physics needs to be enabled on group/sprite in your create function.

 

var xVelocity=0;

var yVelocity=0;

 

function update()

{

snake.body.velocity.x=xVelocity;

snake.body.velocity.y=yVelocity;

 

 if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {       // do the same for other directions changing xVelocity and yVelocity to correct values

//set both velocities of body so sprite travels only in single direction

                    xVelocity=-200;
                    yVelocity=0;
                }

//collision handler to change direction on collide with wall

 game.physics.arcade.collide(snake, wall, collisionHandler, null, this);

 

}

 

 function collisionHandler(obj1,obj2)

{

if(xVelocity==0)

  {

  xVelocity=200;

  yVelocity=0;

  }

else

{

  xVelocity=0;

  yVelocity=200;

}

}

 

this code should get you started.

 

there will be a few bugs and problems with movement but that can be fixed by changing or adding in more checks on the snakes velocity or position

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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