Phaser-圆形路径

使用 Phaser 创建一个简单的路径动画

Phaser 是一个强大的 HTML5 游戏框架,适合用于开发 2D 游戏。在本文中,我们将展示如何使用 Phaser 创建一个简单的动画示例,其中一个红色的圆沿着椭圆路径移动。该示例将帮助你理解如何在 Phaser 中使用路径和补间动画。

前置准备

首先,确保你已经在项目中引入了 Phaser 库。如果你还没有 Phaser,可以通过以下方式之一引入:

  1. 通过 CDN 引入:

    <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
    
  2. 通过 npm 安装:

    npm install phaser
    

示例代码

下面是完整的示例代码,它创建了一个动画场景,其中一个红色圆圈沿着椭圆路径移动:

class Example extends Phaser.Scene {
    graphics;
    path;
    follower;

    create () {
        // 创建一个图形对象,用于绘制路径和圆
        this.graphics = this.add.graphics();

        // 初始化 follower 对象,包含 t(路径进度)和 vec(当前点的向量)
        this.follower = { t: 0, vec: new Phaser.Math.Vector2() };

        // 创建一个路径对象
        this.path = new Phaser.Curves.Path();

        // 在路径上添加一个椭圆(中心在 (400, 300),半径为 100)
        this.path.add(new Phaser.Curves.Ellipse(400, 300, 100));

        // 创建一个补间动画,让 follower 对象在路径上来回移动
        this.tweens.add({
            targets: this.follower,  // 动画目标
            t: 1,                    // 动画结束时 t 的值(路径进度)为 1
            ease: 'Sine.easeInOut',  // 使用正弦缓动函数
            duration: 4000,          // 动画持续时间 4 秒
            yoyo: true,              // 动画结束后反向播放
            repeat: -1               // 无限循环
        });
    }

    update () {
        // 清空之前绘制的内容
        this.graphics.clear();
        // 设置线条样式(白色,宽度为 2)
        this.graphics.lineStyle(2, 0xffffff, 1);

        // 绘制路径
        this.path.draw(this.graphics);

        // 获取路径上当前进度 t 对应的点的坐标,存储在 follower.vec 中
        this.path.getPoint(this.follower.t, this.follower.vec);

        // 设置填充样式(红色)
        this.graphics.fillStyle(0xff0000, 1);
        // 在路径上当前点的坐标位置绘制一个半径为 12 的圆
        this.graphics.fillCircle(this.follower.vec.x, this.follower.vec.y, 12);
    }
}

// 配置 Phaser 游戏实例
const config = {
    type: Phaser.AUTO,                // 渲染类型(自动选择 WebGL 或 Canvas)
    width: 800,                       // 游戏宽度
    height: 600,                      // 游戏高度
    backgroundColor: '#2a2d2a',       // 背景颜色
    parent: 'phaser-example',         // 父元素 ID,用于将游戏画布添加到该元素中
    scene: Example                    // 使用的场景类
};

// 创建 Phaser 游戏实例
const game = new Phaser.Game(config);

效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寻找优秀的自己

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值