2D跟随3D

1、准备控制类:CoordinateUi3D,整体文件已上传

2、准备好创景

 

 

把当前的转向控制类,绑定到上图中的 类 上,

  

 

 3、然后分别绑定2d canvas 摄像头,和3D主摄像头。

  

 

 

 

 

 
 
 
 
 
 
 

import { _decorator, Component, Node, CameraComponent, Vec3, BlockInputEvents } from 'cc';
import { LoadManager } from '../../common/manager/LoadManager';
import { OperateControl } from './OperateControl';
import { GoodsType } from './OperateHelper';
import { OperateStartView } from './OperateStartView';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = CoordinateUi3D
 * DateTime = Fri Apr 22 2022 13:50:43 GMT+0800 (中国标准时间)
 * Author = jiaxin2019
 * FileBasename = CoordinateUi3D.ts
 * FileBasenameNoExtension = CoordinateUi3D
 * URL = db://assets/script/game/operate/CoordinateUi3D.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *  2d界面跟随3D物体位置变化控制类:(像人物的血条,名字等)
 */
const _v3_0 = new Vec3();

@ccclass('CoordinateUi3D')
export class CoordinateUi3D extends Component {
    // @property({ type: Node })
    public D3Node: Node = null!;

    // @property({ type: Node })
    public UINode: Node = null!;

    @property({ type: CameraComponent })
    public mainCamera: CameraComponent = null!;

    @property({ type: Node })
    public canvas: Node = null!;

    private _click3DNode: Node = null!;
    start(): void {
        let t = this;
        t._click3DNode = t.D3Node;
    }

    lateUpdate(deltaTime: number) {
        if (this._click3DNode && this.UINode && this.UINode.active) {
            this._click3DNode.getWorldPosition(_v3_0);
            _v3_0.y += .5;
            this.mainCamera.convertToUINode(_v3_0, this.UINode.parent!, _v3_0);
            this.UINode.setPosition(_v3_0);
        }
    }

    get curClick3DNode(): Node {
        return this._click3DNode;
    }

    set curClick3DNode(val: Node) {
        this._click3DNode = val;
    }

    public setOperatePre(type: GoodsType, canMove: boolean = false): void {
        let prefabName: string = "prefab/OperarionView";
        if (this.UINode) {
            this.viewVs = true;
            this.blockEvents(true);
            let ts = this.UINode.getComponent(OperateStartView);
            ts && (ts.goodsType(type, canMove));
            return;
        }
        LoadManager.loadPrefabOnce(prefabName, this.canvas)
            .then((view) => {
                this.UINode = view;
                this.blockEvents(true);

                let ts = this.UINode.getComponent(OperateStartView);
                ts && (ts.goodsType(type, canMove));
            });

    }

    private blockEvents(enable = false): void {
        let blockEvents = this.canvas.getComponent(BlockInputEvents);
        blockEvents && (blockEvents.enabled = enable);
    }

    set viewVs(b: boolean) {
        this.UINode.active = b;
    }

    get viewVs(): boolean {
        return this.UINode.active;
    }
}
posted @ 2022-05-25 14:19  jiaxin2015  阅读(81)  评论(0)    收藏  举报