phaserjs游戏开发之camera原理

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Phaser.js Camera Example</title>
  <script src="https://cdn.jsdelivr.net/npm/phaser@3/dist/phaser.min.js"></script>
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>
<body>
<script>
  // 配置 Phaser 游戏
  const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
      default: 'arcade',
      arcade: {
        debug: false
      }
    },
    scene: {
      preload: preload,
      create: create,
      update: update
    }
  };

  const game = new Phaser.Game(config);

  let player;      // 玩家对象
  let cursors;     // 键盘输入
  let objects;     // 游戏中的对象组
  let camera;      // 摄像机

  // 游戏世界的大小
  const WORLD_WIDTH = 2000;
  const WORLD_HEIGHT = 1500;

  function preload() {
    // 加载资源(如果有自定义图像,可以在这里加载)
    this.load.image('player', 'https://phaser.io/images/sprites/phaser-dude.png');
    this.load.image('object', 'https://phaser.io/images/sprites/block.png');
  }

  function create() {
    // 设置游戏世界的边界
    this.physics.world.setBounds(0, 0, WORLD_WIDTH, WORLD_HEIGHT);

    // 添加多个随机对象
    objects = this.physics.add.staticGroup();
    for (let i = 0; i < 50; i++) {
      const x = Phaser.Math.Between(0, WORLD_WIDTH);
      const y = Phaser.Math.Between(0, WORLD_HEIGHT);
      const object = objects.create(x, y, 'object').setScale(0.5).refreshBody();
    }

    // 创建玩家
    player = this.physics.add.sprite(400, 300, 'player');
    player.setCollideWorldBounds(true); // 限制玩家在世界范围内移动

    // 添加摄像机并让其跟随玩家
    camera = this.cameras.main;
    camera.startFollow(player);
    camera.setBounds(0, 0, WORLD_WIDTH, WORLD_HEIGHT); // 限制摄像机边界

    // 添加键盘输入
    cursors = this.input.keyboard.createCursorKeys();
  }

  function update() {
    // 玩家移动逻辑
    const speed = 300; // 玩家速度
    player.setVelocity(0);

    if (cursors.left.isDown) {
      player.setVelocityX(-speed);
    } else if (cursors.right.isDown) {
      player.setVelocityX(speed);
    }

    if (cursors.up.isDown) {
      player.setVelocityY(-speed);
    } else if (cursors.down.isDown) {
      player.setVelocityY(speed);
    }
  }
</script>
</body>
</html>

你可能感兴趣的:(游戏开发,phaserjs)