phaserjs+typescript游戏开发之camera实现

以下是一个使用 Phaser.jsTypeScript 实现的示例,包含玩家移动、摄像机跟随并限制在游戏世界范围内的基本功能。

TypeScript 和 Phaser.js 实现的完整代码

  1. 安装 Phaser.js(使用 npm)

首先,确保你已经安装了 Node.jsnpm。然后在你的项目中安装 Phaser.js:

复制代码
bash复制编辑npm init -y
npm install phaser
  1. 项目结构

假设你有以下项目结构:

复制代码
bash复制编辑/your-project
  /src
    index.ts
  /dist
    index.html
  package.json
  1. TypeScript 代码:index.ts

    typescript复制编辑import Phaser from 'phaser';

    class MainScene extends Phaser.Scene {
    private player: Phaser.Physics.Arcade.Sprite;
    private cursors: Phaser.Types.Input.Keyboard.CursorKeys;
    private objects: Phaser.Physics.Arcade.StaticGroup;
    private camera: Phaser.Cameras.Scene2D.Camera;

    private readonly WORLD_WIDTH = 2000;
    private readonly WORLD_HEIGHT = 1500;

    constructor() {
    super('mainScene');
    }

    preload() {
    this.load.image('player', 'https://phaser.io/images/sprites/phaser-dude.png');
    this.load.image('object', 'https://phaser.io/images/sprites/block.png');
    }

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

    复制代码
     // 创建随机对象
     this.objects = this.physics.add.staticGroup();
     for (let i = 0; i < 50; i++) {
       const x = Phaser.Math.Between(0, this.WORLD_WIDTH);
       const y = Phaser.Math.Between(0, this.WORLD_HEIGHT);
       const object = this.objects.create(x, y, 'object').setScale(0.5).refreshBody();
     }
    
     // 创建玩家对象
     this.player = this.physics.add.sprite(400, 300, 'player');
     this.player.setCollideWorldBounds(true);
    
     // 创建摄像机并让其跟随玩家
     this.camera = this.cameras.main;
     this.camera.startFollow(this.player);
     this.camera.setBounds(0, 0, this.WORLD_WIDTH, this.WORLD_HEIGHT);
    
     // 设置键盘输入
     this.cursors = this.input.keyboard.createCursorKeys();

    }

    update() {
    const speed = 300;

    复制代码
     // 初始化玩家速度
     this.player.setVelocity(0);
    
     if (this.cursors.left.isDown) {
       this.player.setVelocityX(-speed);
     } else if (this.cursors.right.isDown) {
       this.player.setVelocityX(speed);
     }
    
     if (this.cursors.up.isDown) {
       this.player.setVelocityY(-speed);
     } else if (this.cursors.down.isDown) {
       this.player.setVelocityY(speed);
     }

    }
    }

    const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
    default: 'arcade',
    arcade: {
    debug: false,
    },
    },
    scene: MainScene,
    };

    const game = new Phaser.Game(config);

  2. HTML 文件:index.html

dist 目录中,创建一个简单的 HTML 文件,用于加载和启动 Phaser 游戏。

复制代码
html复制编辑<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Phaser 3 + TypeScript Example</title>
  <script src="https://cdn.jsdelivr.net/npm/phaser@3/dist/phaser.min.js"></script>
</head>
<body>
  <script src="dist/index.js"></script>
</body>
</html>
  1. TypeScript 配置文件:tsconfig.json

创建一个 tsconfig.json 文件以配置 TypeScript:

复制代码
json复制编辑{
  "compilerOptions": {
    "target": "ES6",
    "module": "ES6",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "baseUrl": "./src"
  },
  "include": ["src/**/*.ts"]
}
  1. 构建和运行项目

首先,编译 TypeScript 文件并启动本地服务器。

  1. 安装开发依赖:

    bash

    复制编辑
    npm install --save-dev typescript http-server

  2. 编译 TypeScript 文件:

    bash

    复制编辑
    npx tsc

这将把 TypeScript 文件编译成 dist 目录中的 index.js 文件。

  1. 启动本地服务器:

    bash

    复制编辑
    npx http-server ./dist

然后,访问 http://localhost:8080 来查看你的 Phaser 游戏。


代码讲解

  1. Phaser 配置:

    复制代码
    typescript复制编辑const config: Phaser.Types.Core.GameConfig = {
      type: Phaser.AUTO,
      width: 800,
      height: 600,
      physics: {
        default: 'arcade',
        arcade: { debug: false },
      },
      scene: MainScene,
    };
    • type: Phaser.AUTO:根据浏览器支持自动选择 WebGL 或 Canvas 渲染。
    • widthheight:设置游戏画布的大小。
    • physics:启用 Arcade 物理引擎并关闭调试模式。
    • scene: MainScene:指定使用 MainScene 类作为游戏的场景。
  2. MainScene 类:

    MainScene 继承自 Phaser.Scene,并实现了游戏的主要逻辑。

    • preload:加载资源(玩家和对象的图像)。
    • create:创建游戏对象,设置物理世界边界,初始化玩家和摄像机。
    • update:每帧更新玩家的位置,处理键盘输入。
  3. 摄像机跟随:

    复制代码
    typescript复制编辑this.camera.startFollow(this.player);
    this.camera.setBounds(0, 0, this.WORLD_WIDTH, this.WORLD_HEIGHT);
    • startFollow:让摄像机跟随玩家。
    • setBounds:设置摄像机的视野范围,限制在世界边界内。
  4. 玩家控制:

    复制代码
    typescript复制编辑if (this.cursors.left.isDown) {
      this.player.setVelocityX(-speed);
    }

    使用键盘的箭头键控制玩家移动,通过 setVelocityXsetVelocityY 设置玩家的速度。


运行效果

  1. 玩家可以通过键盘箭头键在游戏世界中移动。
  2. 摄像机会自动跟随玩家,且受到游戏世界边界的限制。
  3. 游戏界面会呈现一个 800x600 的视图,玩家和一些随机生成的静态对象会被渲染出来。

扩展建议

  1. 添加更多的游戏对象,如敌人、道具等。
  2. 实现碰撞检测,例如玩家与对象、敌人之间的碰撞。
  3. 摄像机缩放 ,可以通过 camera.setZoom() 实现视野缩放。
  4. UI 元素,比如得分、生命值、提示文本等。

通过这个框架,你可以使用 Phaser.js 和 TypeScript 创建一个简单的 2D 游戏,并在此基础上添加更多的功能。

相关推荐
你的人类朋友1 小时前
【Node】认识一下Node.js 中的 VM 模块
前端·后端·node.js
Cosolar1 小时前
FunASR 前端语音识别代码解析
前端·面试·github
@大迁世界4 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
芭拉拉小魔仙4 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
jump_jump4 小时前
妙用 localeCompare 获取汉字拼音首字母
前端·javascript·浏览器
U.2 SSD5 小时前
Echarts单轴坐标系散点图
前端·javascript·echarts
不做无法实现的梦~5 小时前
jetson刷系统之后没有浏览器--解决办法
开发语言·javascript·ecmascript
德育处主任Pro5 小时前
前端玩转大模型,DeepSeek-R1 蒸馏 Llama 模型的 Bedrock 部署
前端·llama
Jedi Hongbin5 小时前
Three.js NodeMaterial 节点材质系统文档
前端·javascript·three.js·nodematerial
前端小马5 小时前
前后端Long类型ID精度丢失问题
java·前端·javascript·后端