const {ccclass, property} = cc._decorator;

export function addTouchEvent(com) {
    com.node.on(cc.Node.EventType.TOUCH_START, com.onTouchStart, com);
    com.node.on(cc.Node.EventType.TOUCH_MOVE, com.onTouchMove, com);
    com.node.on(cc.Node.EventType.TOUCH_END, com.onTouchEnd, com);
    com.node.on(cc.Node.EventType.TOUCH_CANCEL, com.onTouchEnd, com);
    // onTouchStart(eve:cc.Event.EventTouch){
    //
    // }
    // onTouchMove(eve:cc.Event.EventTouch){
    //
    // }
    // onTouchEnd(eve:cc.Event.EventTouch){
    //
    // }
}

@ccclass
export default class Helloworld extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    text: string = 'hello';

    @property(cc.Prefab)
    bulletPf:cc.Prefab=null

    player
    isPress=false

    moveVector

    playerVel=0

    velStr:cc.Label
    onLoad(){
        cc.director.getPhysicsManager().gravity = cc.v2(0,0);
        cc.director.getPhysicsManager().enabled = true;

        this.velStr=cc.find("Vel").getComponent(cc.Label)
    }
    start () {
        this.moveVector=cc.v2()
        this.label.string = this.text;

        this.player=cc.find("World/Player")

        cc.game.setFrameRate(30)


        addTouchEvent(this)
    }

    update(dt){
        let rigidBody=this.player.getComponent(cc.RigidBody)
        if (this.moveVector.x==0) {
            rigidBody.linearVelocity = cc.v2();
        }else {
            let addV=500
            // if(cc.sys.platform==cc.sys.WECHAT_GAME){
            //     addV=2000
            // }
            rigidBody.applyLinearImpulse(this.moveVector.mul(addV), this.player.position, true);
            let curSpeed = rigidBody.linearVelocity;
            // rigidBody.linearVelocity=this.moveVector.mul(500)
            let curVelocity = curSpeed.mag();
            let limit=500
            // if(cc.sys.platform==cc.sys.WECHAT_GAME) {
            //     limit=1000
            // }
            if (curVelocity > limit) {
                let newvec = curSpeed.normalize().mul(limit)
                rigidBody.linearVelocity = newvec;
            }
        }
    }

    lastPos
    showCnt=0
    lateUpdate(dt){



        if(!this.lastPos)
            this.lastPos=this.player.getPosition()

        this.showCnt+=dt
        if(this.showCnt>0.5) {
            this.velStr.string = String(Math.round(this.player.position.sub(this.lastPos).mag() / dt))
            this.showCnt=0
        }
        this.lastPos=this.player.getPosition()
    }

    onTouchStart(eve:cc.Event.EventTouch){
        this.isPress=true
        let n=eve.getLocation()
        if(n.x>960/2){
            this.moveVector=cc.v2(1,0)
        }else{
            this.moveVector=cc.v2(-1,0)
        }
    }
    onTouchMove(eve:cc.Event.EventTouch){

    }
    onTouchEnd(eve:cc.Event.EventTouch){
        this.isPress=false
        this.moveVector=cc.v2()

    }

}
