Advertisement
here2share

$ basic 2D game example

Sep 11th, 2022
924
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* basic 2D game example */
  2. var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
  3. function preload() {
  4.   game.load.image('sky', 'assets/sky.png');
  5.   game.load.image('ground', 'assets/platform.png');
  6.   game.load.image('star', 'assets/star.png');
  7.   game.load.spritesheet('dude', 'assets/dude.png', 32, 48);
  8. }
  9. var platforms;
  10. var player;
  11. var cursors;
  12. var stars;
  13. var score = 0;
  14. var scoreText;
  15. function create() {
  16.   game.physics.startSystem(Phaser.Physics.ARCADE);
  17.   game.add.sprite(0, 0, 'sky');
  18.   platforms = game.add.group();
  19.   platforms.enableBody = true;
  20.   var ground = platforms.create(0, game.world.height - 64, 'ground');
  21.   ground.scale.setTo(2, 2);
  22.   ground.body.immovable = true;
  23.   var ledge = platforms.create(400, 400, 'ground');
  24.   ledge.body.immovable = true;
  25.   ledge = platforms.create(-150, 250, 'ground');
  26.   ledge.body.immovable = true;
  27.   player = game.add.sprite(32, game.world.height - 150, 'dude');
  28.   game.physics.arcade.enable(player);
  29.   player.body.bounce.y = 0.2;
  30.   player.body.gravity.y = 300;
  31.   player.body.collideWorldBounds = true;
  32.   player.animations.add('left', [0, 1, 2, 3], 10, true);
  33.   player.animations.add('right', [5, 6, 7, 8], 10, true);
  34.   cursors = game.input.keyboard.createCursorKeys();
  35.   stars = game.add.group();
  36.   stars.enableBody = true;
  37.   for (var i = 0; i < 12; i++) {
  38.     var star = stars.create(i * 70, 0, 'star');
  39.     star.body.gravity.y = 6;
  40.     star.body.bounce.y = 0.7 + Math.random() * 0.2;
  41.   }
  42.   scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
  43. }
  44. function update() {
  45.   game.physics.arcade.collide(player, platforms);
  46.   game.physics.arcade.collide(stars, platforms);
  47.   game.physics.arcade.overlap(player, stars, collectStar, null, this);
  48.   player.body.velocity.x = 0;
  49.   if (cursors.left.isDown) {
  50.     player.body.velocity.x = -150;
  51.     player.animations.play('left');
  52.   } else if (cursors.right.isDown) {
  53.     player.body.velocity.x = 150;
  54.     player.animations.play('right');
  55.   } else {
  56.     player.animations.stop();
  57.     player.frame = 4;
  58.   }
  59.   if (cursors.up.isDown && player.body.touching.down) {
  60.     player.body.velocity.y = -350;
  61.   }
  62. }
  63. function collectStar(player, star) {
  64.   star.kill();
  65.   score += 10;
  66.   scoreText.text = 'Score: ' + score;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement