Pobtastic / Goldfish Game / Player

Created Sun, 21 Apr 2024 15:35:15 +0100 Modified Sat, 04 May 2024 21:31:28 +0000

Introduction

As with all the images, preload first:

  preload() {
    // Preload the player assets.
    for (let i = 1; i <= 8; i++) {
      this.load.image(`swimmer-${i}`, `/images/booty/swimmer-${i}.png`);
    }
  }

I’ve left the “sea” rectangle in here, just so you can see that the world bounds use the exact same measurements:

  create() {
    // Add the "sea"!
    this.add.rectangle(0, 8 * 8 * this.gameScale, config.width, 8 * 12 * this.gameScale, 0x0000C5).setOrigin(0, 0);

    // The player can only move within the "sea" area.
    this.physics.world.setBounds(0, 8 * 8 * this.gameScale, config.width, 8 * 12 * this.gameScale);

    // Create the player sprite.
    this.player = this.physics.add.sprite(400, 300, 'swimmer-1');
    this.player.setOrigin(0, 0);

    // Our player should be restricted to only move within the boundaries
    // of the sea area we've defined.
    this.player.setCollideWorldBounds(true);

    // Add the players animation frames.
    const swimFrames = [];
    for (let i = 1; i <= 8; i++) {
      swimFrames.push({ key: `swimmer-${i}` });
    }
    this.anims.create({
      key: 'swim',
      frames: swimFrames,
      // How fast to change frame.
      frameRate: 10,
      // Repeat indefinitely.
      repeat: -1
    });

    // The animation just plays throughout the game.
    this.player.play('swim');

    // Allow the user to move our player using the cursor keys.
    this.cursors = this.input.keyboard.createCursorKeys();
  }

Now define how the player moves:

  update() {
    // Manage moving the player.
    const moveSpeed = 8 * 8 * this.gameScale;

    // Reset velocity every frame to stop movement when no key is pressed.
    this.player.setVelocity(0);

    // Handle left and right.
    if (this.cursors.left.isDown) {
      this.player.setVelocityX(-moveSpeed);
    }
    else if (this.cursors.right.isDown) {
      this.player.setVelocityX(moveSpeed);
    }

    // Handle up and down.
    if (this.cursors.up.isDown) {
      this.player.setVelocityY(-moveSpeed);
    }
    else if (this.cursors.down.isDown) {
      this.player.setVelocityY(moveSpeed);
    }

  }

Which all leads to this! Use the cursor keys to move our player around. The actual game is slightly more quirky with the animation, but as I said before, we’re not trying for a 100% accurate emulation - just a playable approximation to keep this fun!

Booty Disassembly