3DUI Cocos Creator
白玉无冰
共 5214字,需浏览 11分钟
· 2023-03-11
分享一个小组件,实现3DUI~
效果
使用效果、步骤、原理见视频[1]
环境
Cocos Creator 3.7.1
原理
UI相机生成一张RT,动态计算UV生成四方形网格
![](https://filescdn.proginn.com/35df9d263a84196786fabff646e43606/597155bfdc25049a523fb3ac80b84900.webp)
步骤
层级
![](https://filescdn.proginn.com/5cd8da531f01037825266732c20ab8d7/aba01250cfbdc72a39148aad978af01b.webp)
![](https://filescdn.proginn.com/5438f18e575431c8a751bff60f1280a3/c6502d31ee2c154c7f503f97d5ed2254.webp)
相机
![](https://filescdn.proginn.com/320a0b1ab5b19e288d7291aed4ff6d23/b3bd8b4b2a0a333221b4fad51610be03.webp)
材质
![](https://filescdn.proginn.com/b819fce06e1300be88437027f072efb7/f0952df1b87825f7207daf53ffde3dbf.webp)
![](https://filescdn.proginn.com/ee866a6237529a9ffcba2d7aea6ed720/a05f5ddac750093f4061eb607b879643.webp)
组件
![](https://filescdn.proginn.com/3650da5d6e7017e1930d5698c59a8b18/2da4acd1512004507c3ba06b411db84a.webp)
代码
import { _decorator, Component, Node, Camera, RenderTexture, view, UITransform, MeshRenderer, primitives, utils, log } from 'cc';
const { ccclass, property, executeInEditMode } = _decorator;
@ccclass('UIQuadProfile')
export default class UIQuadProfile {
@property(Node)
targetNode: Node = null!;
@property(MeshRenderer)
quad: MeshRenderer = null!
}
@ccclass('UIQuad')
@executeInEditMode
export class UIQuad extends Component {
@property(Camera)
copyCamera: Camera = null!;
@property([UIQuadProfile])
UIQuadProfiles: UIQuadProfile[] = []
rt: RenderTexture
start() {
log('欢迎关注微信公众号【白玉无冰】 https://mp.weixin.qq.com/s/4WwCjWBtZNnONh8hZ7JVDA')
}
onEnable() {
if (!this.copyCamera) return
this.copyCamera.node.active = true;
this.rt = new RenderTexture();
this.rt.reset({
width: view.getVisibleSize().width,
height: view.getVisibleSize().height,
})
this.copyCamera.targetTexture = this.rt;
this.copyRenderTex();
}
onDisable() {
if (!this.copyCamera) return
this.copyCamera.node.active = false;
this.copyCamera.targetTexture = null
this.rt?.destroy()
}
private copyRenderTex() {
this.UIQuadProfiles.forEach((v, i) => {
const targetNode = v.targetNode
const quad = v.quad
if (!targetNode || !quad) return
quad.material.setProperty("mainTexture", this.rt);
const width = targetNode.getComponent(UITransform).width;
const height = targetNode.getComponent(UITransform).height;
const anchorPoint = targetNode.getComponent(UITransform).anchorPoint
const rtwidth = this.rt.width;
const rtheight = this.rt.height;
const worldPos = targetNode.getWorldPosition();
worldPos.x -= width * anchorPoint.x
worldPos.y -= height * anchorPoint.x
const geometryQuad = primitives.quad();
const uv_l = worldPos.x / rtwidth
const uv_b = worldPos.y / rtheight
const uv_r = (worldPos.x + width) / rtwidth
const uv_t = (worldPos.y + height) / rtheight
geometryQuad.uvs = [uv_l, uv_b, uv_l, uv_t, uv_r, uv_t, uv_r, uv_b]
quad.mesh = utils.MeshUtils.createMesh(geometryQuad, quad.mesh)
})
}
}
更多
参考资料
使用效果、步骤、原理见视频: https://www.bilibili.com/video/BV1UM411s751
点击“阅读原文”查看精选导航
“点赞“ ”在看” 鼓励一下▼
评论