cocos creator 模拟点击某个节点

    static touchNode (node:cc.Node) {
        const glPos = node.convertToWorldSpaceAR(cc.v2());
        setTimeout(() => {
            this.touchSimulation(glPos);
        }, 0);
    }

    // 模拟点击
    static touchSimulation (glPos: cc.Vec2) {
        let rect;
        // @ts-ignore
        const inputManager = cc.internal.inputManager;
        if (cc.sys.isBrowser) {
            const canvas = document.getElementById('GameCanvas');
            rect = this.getHTMLElementPosition(canvas);
        } else {
            rect = cc.view.getFrameSize();
            rect.left = 0;
            rect.top = 0;
        }

        const vp = cc.view.getViewportRect();
        const sx = cc.view.getScaleX();
        const sy = cc.view.getScaleY();
        const ratio = cc.view.getDevicePixelRatio();
        const htmlx = (glPos.x * sx + vp.x) / ratio + rect.left;
        const htmly = rect.top + rect.height - (glPos.y * sy + vp.y) / ratio;
        const pt = cc.v2(htmlx, htmly);

        // cc.log(`模拟点击坐标:${pt.x}, ${pt.y}`);
        const touch = inputManager.getTouchByXY(pt.x, pt.y, rect);
        const touchEnd = inputManager.getTouchByXY(pt.x, pt.y, rect);
        inputManager.handleTouchesBegin([touch]);
        inputManager.handleTouchesEnd([touchEnd]);

        // setTimeout(() => {
        //     inputManager.handleTouchesEnd([touch]);
        // }, 100);
    }

 

posted @ 2023-02-24 19:24  Please Call me 小强  阅读(223)  评论(0编辑  收藏  举报