Cocos Creator 3.8 默认使用 TypeScript 作为主要开发语言,下面将详细介绍在微信小游戏开发中 TypeScript 的使用方式和特点。
一、TypeScript 基础配置
1. 项目结构
assets/ ├── scripts/ # TypeScript 代码目录 │ ├── Main.ts # 示例入口文件 │ └── ... # 其他脚本 └── ... # 其他资源
2. tsconfig.json
Cocos Creator 会自动生成 TypeScript 配置文件,主要配置包括:
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"lib": ["es2018", "dom"],
"types": ["cc", "@types/node"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"@/*": ["./assets/*"]
}
},
"include": ["assets/**/*.ts"],
"exclude": ["node_modules"]
}
二、核心 TypeScript 特性应用
1. 组件定义
// 定义组件
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('PlayerController')
export class PlayerController extends Component {
@property(Node)
private targetNode: Node | null = null;
@property({ type: Number, tooltip: '移动速度' })
public moveSpeed: number = 10;
private _direction: Vec3 = new Vec3();
start() {
// 初始化逻辑
}
update(deltaTime: number) {
// 每帧更新逻辑
}
}
2. 接口与类型
// 定义游戏数据接口
interface IGameData {
score: number;
level: number;
inventory: string[];
}
// 实现接口
class GameManager implements IGameData {
score: number = 0;
level: number = 1;
inventory: string[] = [];
private static _instance: GameManager;
public static get instance(): GameManager {
if (!this._instance) {
this._instance = new GameManager();
}
return this._instance;
}
}
三、微信小游戏特有 TypeScript 集成
1. 声明微信 API
// 扩展微信类型声明
declare namespace wx {
function getSystemInfoSync(): {
SDKVersion: string;
batteryLevel: number;
brand: string;
// 其他属性...
};
function onShow(callback: (res: { scene: number }) => void): void;
function onHide(callback: () => void): void;
// 其他API声明...
}
2. 平台相关代码处理
class PlatformAdapter {
static login(): Promise<{ code: string }> {
if (CC_WECHATGAME) {
return new Promise((resolve) => {
wx.login({
success: (res) => resolve(res)
});
});
} else {
// 其他平台处理
return Promise.resolve({ code: 'test_code' });
}
}
}
四、高级 TypeScript 特性应用
1. 泛型在对象池中的应用
class ObjectPool<T> {
private _pool: T[] = [];
private _creator: () => T;
constructor(creator: () => T) {
this._creator = creator;
}
get(): T {
return this._pool.pop() || this._creator();
}
put(obj: T): void {
this._pool.push(obj);
}
}
// 使用示例
const bulletPool = new ObjectPool<Bullet>(() => new Bullet());
const bullet = bulletPool.get();
2. 装饰器增强功能
// 性能分析装饰器
function profile(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const end = performance.now();
console.log(`${propertyKey} 执行耗时: ${(end - start).toFixed(2)}ms`);
return result;
};
return descriptor;
}
class GameLogic {
@profile
calculateDamage(attacker: Player, defender: Enemy): number {
// 复杂计算逻辑...
}
}
五、模块化开发实践
1. 使用 ES 模块
// assets/scripts/utils/MathUtils.ts
export class MathUtils {
static clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
}
// 在其他文件中使用
import { MathUtils } from '@/utils/MathUtils';
const value = MathUtils.clamp(10, 0, 5);
2. 异步编程模式
// 使用async/await处理微信API
async function loadRemoteConfig(): Promise<GameConfig> {
try {
if (CC_WECHATGAME) {
const res = await wx.request({
url: 'https://example.com/config',
method: 'GET'
});
return res.data as GameConfig;
}
// 其他平台处理...
} catch (error) {
console.error('加载配置失败:', error);
return getDefaultConfig();
}
}
六、调试与类型安全
1. 类型断言
// 处理微信返回数据
const systemInfo = wx.getSystemInfoSync() as {
platform: 'ios' | 'android' | 'devtools';
pixelRatio: number;
};
// 节点类型断言
const playerNode = this.node.getChildByName('Player') as Node;
2. 严格空检查
// 启用strictNullChecks后
class GameUI {
private _scoreLabel: Label | null = null;
start() {
this._scoreLabel = this.node.getComponent(Label);
if (!this._scoreLabel) {
console.error('Score Label组件未找到!');
return;
}
// 现在可以安全使用_scoreLabel
this._scoreLabel.string = '100';
}
}
七、与Cocos Creator引擎的深度集成
1. 组件属性类型
@ccclass
class GameItem extends Component {
@property({ type: SpriteFrame })
icon: SpriteFrame | null = null;
@property({ type: [String] }) // 字符串数组
tags: string[] = [];
@property({ type: Node })
effectNode: Node | null = null;
}
2. 使用引擎类型系统
import { Vec3, Quat, math } from 'cc';
class CharacterMovement {
private _velocity: Vec3 = new Vec3();
move(direction: Vec3, speed: number): void {
Vec3.normalize(this._velocity, direction);
Vec3.multiplyScalar(this._velocity, this._velocity, speed);
// 使用引擎数学工具
const rotation = Quat.rotationTo(new Quat(), Vec3.FORWARD, direction);
this.node.setRotation(rotation);
}
}
通过以上TypeScript实践,你可以充分利用强类型系统的优势,在Cocos Creator 3.8中开发出更健壮、更易维护的微信小游戏代码。记得定期检查Cocos TypeScript API文档获取最新的类型定义信息。