
import { __private, Component, _decorator, Node, Prefab, instantiate, PhysicsSystem, Vec3, UICoordinateTrackerComponent, EventHandler, EventTouch, SpriteComponent, Sprite, SpriteFrame, Camera, Label, v3 } from "cc";
const { ccclass, property } = _decorator;

/**位置映射到UI节点,并自动更新该UI节点的位置*/
@ccclass('PositionMapToUIComponent')
export class PositionMapToUIComponent extends Component {
    public targetUI!: Node;
    public camera!: Camera;

    protected _canMove = true;
    private _lastCameraPos: Vec3 = v3();
    private _lastWPos: Vec3 = v3();
    private _transformUIPos: Vec3 = v3();
    private _testPos: Vec3 = v3();

    start() {
    }
    onEnable() {
        this._checkCanMove();
    }
    protected _checkCanMove() {
        this._canMove = !!(this.camera && this.targetUI);
    }

    update() {
        const wPos = this.node.worldPosition;
        const camera = this.camera;
        if (!this._canMove || !camera || !camera.camera || (this._lastWPos.equals(wPos) && this._lastCameraPos.equals(camera.node.worldPosition))) {
            return;
        }
        this._lastWPos.set(wPos);
        this._lastCameraPos.set(camera.node.worldPosition);
        // [HACK]
        camera.camera.update();
        camera.convertToUINode(wPos, this.targetUI, this._transformUIPos);//this._transformUIPos这值一下异常一下正常
        camera.worldToScreen(wPos, this._testPos);
        /*
        if (this._useScale) {
            Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera.camera.matView);
        }*/
        /*
        if (this.syncEvents.length > 0) {
            const data = this._distance / Math.abs(this._viewPos.z);
            EventHandler.emitEvents(this.syncEvents, this._transformUIPos, data);
        }*/

        //先简单的直接更新UI节点位置
        this._transformUIPos.z = 0;
        this.targetUI.setPosition(this._transformUIPos);
        //this._testPos.z = 0;
        //this.targetUI.setPosition(this._testPos);

    }
}