import { _decorator, Component, Node, Vec3, director, CameraComponent } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CameraUtils')
export class CameraUtils extends Component {
    /* class member could be defined like this */
    // dummy = '';

    /* use `property` decorator if your want the member to be serializable */
    // @property
    // serializableDummy = 0;
    private min:Vec3;
    private max:Vec3;
    private out:Vec3=new Vec3();

    private startTime:number;
    private endTime:number;
    private startPos:Vec3=new Vec3();

    private shakeing:boolean;

    private camera:CameraComponent;
    /**
     * 抖动
     * @param time  持续时间
     * @param min   最小值
     * @param max   最大值
     */
    shake(time:number,min:Vec3,max:Vec3):void{
        this.min=min;
        this.max=max;
        this.startTime=director.getCurrentTime();
        this.endTime=this.startTime+time;
        this.shakeing=true;
        this.startPos.set(this.node.position.x,this.node.position.y,this.node.position.z);
        this.camera=this.node.getComponent(CameraComponent);
    }

    start () {
        // Your initialization goes here.
    }

    update (deltaTime: number) {
        if(this.shakeing){
            let currentTime:number=director.getCurrentTime();
            if(currentTime<this.endTime){
                this.randomV3(this.min,this.max,this.out);
                this.out.x+=this.startPos.x;
                this.out.y+=this.startPos.y;
                this.out.z+=this.startPos.z;
                this.node.position=this.out;
            }else{
                this.node.position=this.startPos;
            }
        }
    }

    private randomV3(min:Vec3,max:Vec3,out:Vec3):void{
        let dx:number=max.x-min.x;
        let dy:number=max.y-min.y;
        let dz:number=max.z-min.z;
        out.x=min.x+Math.random()*dx;
        out.y=min.y+Math.random()*dy;
        out.z=min.z+Math.random()*dz;
    }
}
