phaserjs+typescript游戏开发之camera实现

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

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

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

首先,确保你已经安装了 Node.js 和 npm。然后在你的项目中安装 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 渲染。
    • width 和 height:设置游戏画布的大小。
    • 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);
    }

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


运行效果

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

扩展建议

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

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

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万5 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁5 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄5 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95275 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大5 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师5 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端