重力传感事件应用之一 手机摇一摇(摇一次得一分)

手机摇动算法:摇一次只要 x 或y 正负之间变化并超过指定的幅度,就得一分。

        cc.inputManager.setAccelerometerEnabled(true);
        cc.systemEvent.on(cc.SystemEvent.EventType.DEVICEMOTION, this.onDeviceMotionEvent, this);

    onDeviceMotionEvent :function (event) {
        var nowGX = event.acc.x.toFixed(2);
        var nowGY = event.acc.y.toFixed(2);
        var nowGZ = event.acc.z.toFixed(2);


        if(this._isGetScore3(nowGX,nowGY)){
            this.score += 1;
            this.scoreDisplay.string = this.score.toString();
        }


    },


    _isGetScore3(nowGX,nowGY){
        var stand_x = 0.25;
        var stand_y = 0.25;
        if(this.x_prev_tag){  //前一次为 正 
            stand_x = -stand_x;

            if(nowGX <= stand_x){
                var cur_x_tag = false;
            }else{
                var cur_x_tag = true;
            }
        }else {    //前一次为负
            if(nowGX >= stand_x){
                var cur_x_tag = true;
            }else{
                var cur_x_tag = false;
            }
        }

        if(this.y_prev_tag){  //前一次为 正 
            stand_y = -stand_y;

            if(nowGY <= stand_y){
                var cur_y_tag = false;
            }else{
                var cur_y_tag = true;
            }
        }else {    //前一次为负
            if(nowGY >= stand_y){
                var cur_y_tag = true;
            }else{
                var cur_y_tag = false;
            }
        }



        var x_is = false;
        var y_is = false;
        if(( this.x_prev_tag == true && cur_x_tag == false) ||
            (this.x_prev_tag == false && cur_x_tag == true)
        ){

            //console.log('x prev:cur==',this.x_prev_val, '##',nowGX);
            this.x_prev_val = nowGX;
            this.x_prev_tag = cur_x_tag;
            x_is = true;
        }

        if((this.y_prev_tag == true && cur_y_tag == false) ||
            (this.y_prev_tag == false && cur_y_tag == true)
        ){
            //console.log('y prev:cur==', this.y_prev_val, '##',nowGY)
            this.y_prev_val = nowGY;
            this.y_prev_tag = cur_y_tag;
            y_is = true;
        }

        return x_is || y_is;


    },

 

你可能感兴趣的:(cocos,creator)