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 游戏,并在此基础上添加更多的功能。

相关推荐
bin91538 分钟前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云2 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一2 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球2 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7232 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中3 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19004 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端4 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead5 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多5 小时前
案例自定义tabBar
前端