The cocos creator health bar follows the problem caused by 3d convertToUINode, use worldToScreen to solve the following deviation problem

cocos creator 3.3.2, to follow the blood bar, the camera’s convertToUINode used at the beginning is also operated according to the blog of Master Qilinzi, and the final effect is that the blood bar is displayed normally in the middle of the screen, and deviations begin to appear at the edge of the screen, x deviation from both y

 In the end, there was no solution. Later, Master Qilinzi said that this convertToUINode can actually be used. I am not sure whether it is good or not. It is best to use worldToScreen. I finally used this.

full code

@ccclass('PlayerCtrl')
export class PlayerCtrl extends Component {
    @property(CameraComponent)
    cam: CameraComponent = null!;// 照射角色的相机

    @property(RenderTexture)
    render: RenderTexture = null!; // 渲染投射图

    @property(Sprite)
    show3d: Sprite = null!; //  显示投射的ui

    @property([Node])
    player3dHps: Node[] = []; // 所有角色3d血条位置
    @property([Node])
    uiHps: Node[] = []; // 所有血条ui

    start() {
        // 投影 吧3d照射的投影到2d ui上
        const renderTex = this.render;
        this.cam.targetTexture = renderTex;
        this.show3d.spriteFrame.texture = renderTex;
    }

    lateUpdate() {
        // 使用 worldToScreen 实现血条跟随
        this.player3dHps.forEach((item, i) => {
            // 血条
            let ve1 = new Vec3(0, 0, 0)
            this.cam.worldToScreen(item.worldPosition, ve1);
            let design = view.getDesignResolutionSize();
            // 这里就是计算一下  浏览器端屏幕是横屏的,实际我们canvas区域是中间手机屏,而且血条还不能加widget固定死,所有在pc端
            // 转出来的坐标是实际屏幕算的,不是中间手机位置的,我们要计算到中间手机位置的区域,计算出的位置+屏幕左侧到手机屏的左侧的距离,就是中间手机的显示区域
            // 这里计算offsetHeight,是因为手机端是适配宽度,不同机型的实际高度不一,可能血条高于正常值或者低于,所以在这里要-(根据设计分辨率求出的高度-实际屏幕的高度)/2
            // 对于offsetHeight不理解,可以尝试在手机浏览器运行一下就明白了,和pc显示的差别
            let canvasWidget = find("Canvas").getComponent(Widget)
            let offsetHeight = !sys.isMobile?0: ((view.getVisibleSize().width*design.height/design.width)-view.getVisibleSize().height);// 计算出高度比实际分辨率的差距,
            this.uiHps[i].worldPosition = ve1.add(new Vec3(canvasWidget.left,-offsetHeight/2,0));;
        })


        // // 使用convertToUINode 实现血条跟随
        // this.player3dHps.forEach((item, i) => {
        //     // 血条
        //     let ve1 = new Vec3(0, 0, 0)
        //     this.cam.convertToUINode(new Vec3(item.worldPosition), this.uiHps[i].parent, ve1);
        //     this.uiHps[i].setPosition(ve1)
        // })

    }
    // update (deltaTime: number) {
    //     // [4]
    // }
}

Project address   GitHub - SuiFengErQu/cocos-creator3d-mini_demo: cocos creator3.3.2 hand practice small function       adaptationScreen scene

Guess you like

Origin blog.csdn.net/github_38633141/article/details/121406438
Recommended