Cocos3x 2D/UI元素跟随3D对象问题

说多都是泪,独自摸索浪费了很多时间,这里做个记录:

关于Cocos3x 2D/UI元素跟随3D对象问题的几个关键点:

  1. 3D节点的缩放旋转会影响2D元素的初始值,所以不要直接在3D元素节点上创建UI元素,在根节点创建空节点挂载UI组件。或者先在根节点创建好UI元素,再拖拽到3D元素的节点下。
  2. Camera.convertToUINode方法前两个参数一个是3D元素的世界坐标,另一个是UI节点。
  3. UI元素最好都放在同一个节点下的Canvas里,否则Drawcall会飙升。

这里写了一个2/3D跟随通用脚本:

(包括相机跟随3D目标也能用)

import { _decorator, Camera, Component, Node, Vec3, view } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FollowTarget')
export class FollowTarget extends Component {
    @property(Boolean)
    is2DNode:boolean = false;

    @property(Node)
    target:Node;

    // 偏移,默认值为相机偏移值
    @property(Vec3)
    offset:Vec3 = new Vec3(0, 120, -180);

    // 主相机,2d节点需要
    @property(Camera)
    mainCamera:Camera;

    start() {
        console.log('FollowTarget', this.node, this.target);
    }

    update(deltaTime: number) {
        const tmpPos = new Vec3();
        
        // ******************** 2d节点 ********************
        if(this.is2DNode){
            // 获取目标3D对象的世界坐标
            const worldPos = this.target.getWorldPosition();
            const uiPos = this.mainCamera.convertToUINode(worldPos, this.node.parent);

            // 更新UI节点的位置
            this.node.setPosition(uiPos.add(this.offset));
            return;
        }

        this.target.getPosition(tmpPos);
        tmpPos.add(this.offset);
        this.node.position = tmpPos;
    }
}

 

posted @ 2025-07-01 15:45  我的五年  阅读(23)  评论(0)    收藏  举报