
import { _decorator, Component, Node, UITransform, Camera,Vec3,Rect } from 'cc';
import { setting } from './config/setting';
const { ccclass, property } = _decorator;

@ccclass('TiledCanvas')
export class TiledCanvas extends Component {
    
    @property({type:Node})
    private World:Node|null=null;
    @property({type:Node})
        playerNode:Node|null=null;
    @property({type:Node})
        Map:Node|null=null;

    val:Vec3=new Vec3(-15,-10,0);    

    max_x:number=0;
    max_y:number=0;
    mainwidth:number=0;
    mainheight:number=0;
    mapwidth:number=0;
    mapheight:number=0;

    onLoad () {
        
        var fw=setting.instance.getFrameSize().width;//屏幕分辨率
        var fh=setting.instance.getFrameSize().height;
        var dw=setting.instance.getDesignSize().width;//设计分辨率
        var dh=setting.instance.getDesignSize().height;
        
        var rh=setting.instance.getMapPercentage();
        var ry=setting.instance.getMapCameraY();
        var rect=new Rect(0,ry,1,rh);
        this.node.getComponent(Camera).rect=rect;


        this.mainwidth=this.node.parent.getComponent(UITransform).width / 2
        this.mapwidth=this.Map.getComponent(UITransform).width/2;

        this.mainheight=this.node.parent.getComponent(UITransform).width / 2
        this.mapheight=this.Map.getComponent(UITransform).height/2;

        this.max_x=this.mapwidth-this.mainwidth;
        this.max_y=this.mapheight-this.mainheight;


        //console.log(this.node.getPosition());
    }

    update(dt){
        //return
        if(!this.playerNode) return;

        let w_pos = this.playerNode.getComponent(UITransform).convertToWorldSpaceAR(this.val);
        let n_pos = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(w_pos);

        n_pos.z=1000;

        if(n_pos.x-(-this.mainwidth)<=-this.mapwidth){
           n_pos.x=-this.mapwidth+this.mainwidth;
        }else if(n_pos.x+this.mainwidth>=this.mapwidth){
            n_pos.x=this.mapwidth-this.mainwidth;
        }

        if(n_pos.y-60<=-this.max_y){
            n_pos.y=-this.max_y;
        }else if(n_pos.y+60>=this.max_y){
            n_pos.y=this.max_y;
        }
        this.node.position=n_pos;
        
    }
}