最近学上了cocos,开个笔记记录下初学平时常用的内容~
- 代码风格,大小写,规范
- 时间监听后需要关闭监听
1.设置颜色和透明度
this.bg.getComponent(UIOpacity).opacity = 255
this.bg.getComponent(Sprite).color = new Color().fromHEX(color)
2.设置宽高
this.node.getComponent(UITransform).setContentSize(this.itemWidth,this.itemHeight)
3.绘图用graphics组件
// 绘制格子边框
drawGrid(drawNode:Node,gridData:any, startPos:Vec3,cellSize:number) {
const graphics = drawNode.getComponent(Graphics)
graphics.clear()
graphics.lineWidth = 2.5
graphics.strokeColor.fromHEX('#000000') // 设置边框颜色
for(let row = 0; row < gridData.length ; row ++) {
for(let col = 0; col < gridData[row].length ; col ++) {
if(gridData[row][col] === 1) {
// 计算单元格左上角坐标
const x = startPos.x + col * cellSize
const y = startPos.y - row * cellSize
// 定义正方形绘制路径:rect (x, y, w, h)
graphics.rect(x,y,cellSize,cellSize)
graphics.stroke() // 绘制已定义的路径
}
}
}
}
4.旋转
node.angle = 角度
@property(Node)
Target_Node: Node = null; // 获取箭靶节点
Angle = 0 // 旋转角度
Angle_Speed = 50 // 旋转速度
update(deltaTime: number) {
// 角度超过360度,重置角度,避免一直计算浪费性能
if(this.Angle >= 360) {
this.Angle = 0
}
// 箭靶不断旋转
this.Angle += deltaTime * this.Angle_Speed // 设置旋转角度(帧时间补偿,避免不同给设备旋转速度不同)
this.Target_Node.angle = this.Angle
}
5.设置父节点
node.setParent(父节点)
6.预制体生成节点
节点= instantiate(预制体)
7.平滑移动
tween(节点).to(时长秒,{position: new Vec3(3d位置)}).call(回调函数).start()
.call()执行回调
.start()开始移动
8. 获取和设置世界坐标
获取:
节点.getWorldPosition()
设置:
节点.setWorldPosition(世界坐标)
9. 播放和暂停动画
动画组件.play(动画名字)
动画组件.stop()
10.获取音频组件
AudioSource
this.node.getComponent(AudioSource)
11. 播放音频
const Audio = this.node.getComponent(AudioSource) // 获取音频组件
Audio.clip = this.Win_Audio // 指定播放资源
Audio.play() // 开始播放
12. 插屏设置
13.spine动画播放
spine动画播放时需要确保名字与spine动画内部的名字和大小写一致。
let anim = this.node.getComponent(sp.Skeleton);
anim.setCompleteListener(() => {
anim.clearTracks();
this.node.active = false;
this.node.parent.active = false;
// EventMgr.emit("play_anim_over");
})
// 播放动画,动画名称应与spine文件中定义的动画名称一致
anim.setAnimation(0, "Error", false);
编辑器中动画节点以及其父节点都必须打开显示才能看到对应的spine内部名字,否则名字显示为None
显示:
没显示:
14.动态资源加载与使用
// load加载资源后,才用get获取使用
resources.loadDir('texture',() => {
let sp = resources.get('texture/xian1/spriteFrame') as SpriteFrame;
this.xianImg.getComponent(Sprite).spriteFrame = sp;
console.log('sp',sp,idx,`texture/xian${idx}/spriteFrame`);
})
项目中一般会封装BundleManager,管理资源包中的图片、音频、预制体