文章使用ai润色
这套工具包旨在简化 Cocos 3.x 下的 2D 开发流程,扁平化常用属性,并封装轮询输入管理器。利用 TypeScript 类型推导保证 API 安全性,内部复用临时对象以减少 GC 开销,为纯 2D 项目开发提供便利。
安装
npm install cocos-creator-2d-kit
- GitHub 仓库:https://github.com/yxdtg/cocos-creator-2d-kit
- NPM 地址:https://www.npmjs.com/package/cocos-creator-2d-kit
使用示例
一、 全局初始化
在场景启动脚本中调用一次,之后所有组件均可使用 this.node2d。
import { injectionNode2DToGlobalComponent } from 'cocos-creator-2d-kit';
onLoad() {
injectionNode2DToGlobalComponent();
}
二、 Node2D 属性操作
1. 本地变换属性
直接对本地坐标、尺寸、缩放、锚点和旋转进行赋值或获取。
update(dt: number) {
this.node2d.x += 100 * dt;
this.node2d.y = 50;
this.node2d.width = 200;
this.node2d.height = 100;
this.node2d.scaleX = 1.5;
this.node2d.scaleY = 0.5;
this.node2d.anchorX = 0.5;
this.node2d.anchorY = 0.5;
this.node2d.angle += 30 * dt;
this.node2d.rotation = Math.PI / 2;
}
2. 世界坐标与变换
直接读写基于 Canvas 空间的世界坐标及缩放旋转。
update() {
this.node2d.setWorldPosition(500, 300);
const wx = this.node2d.worldX;
this.node2d.worldY = 100;
const wp = this.node2d.worldPosition;
const ws = this.node2d.worldScale;
const wsx = this.node2d.worldScaleX;
const wsy = this.node2d.worldScaleY;
const wa = this.node2d.worldAngle;
const wr = this.node2d.worldRotation;
}
3. 事件绑定与组件管理
事件回调的参数类型与事件类型严格对应,绑定的事件随节点销毁自动注销。
添加组件时传入的初始属性只允许传入组件本身存在且可写的属性。
onLoad() {
this.node2d.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
const sprite = this.node2d.addComponent(Sprite, {
spriteFrame: this.myFrame,
sizeMode: Sprite.SizeMode.CUSTOM
});
const uiTransform = this.node2d.getComponent(UITransform);
this.node2d.removeComponent(Sprite);
}
三、 InputManager 输入管理
1. 键盘输入轮询
update(dt: number) {
if (InputManager.instance.isKeyHold(KeyCode.KEY_D)) {
this.node2d.x += 200 * dt;
}
if (InputManager.instance.isKeyDown(KeyCode.SPACE)) {
this.jump();
}
if (InputManager.instance.isKeyUp(KeyCode.SHIFT)) {
this.stopRunning();
}
}
2. 鼠标输入轮询
获取的鼠标坐标已转换为 Canvas 节点空间下的坐标。
update(dt: number) {
if (InputManager.instance.isMouseHold(BUTTON_TYPE.Left)) {
this.fire();
}
const mousePos = InputManager.instance.mousePosition;
const mx = InputManager.instance.mouseX;
const my = InputManager.instance.mouseY;
}
3. 辅助计算
获取节点指向鼠标的旋转角度。
update(dt: number) {
this.node2d.angle = InputManager.instance.getNode2DOrientationMouseAngle(this.node2d);
}
