belliott554 Posted March 27, 2014 Share Posted March 27, 2014 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 More sharing options...
temporalix Posted March 27, 2014 Share Posted March 27, 2014 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 More sharing options...
belliott554 Posted March 28, 2014 Author Share Posted March 28, 2014 Thanks a lot. The code works just as you said it would. Link to comment Share on other sites More sharing options...
Recommended Posts