天天看點

搖一搖誕生記三(手機重力傳感事件)(cocos creator第一個項目)

這算是開發的第二天了,手機端關鍵功能就是搖一搖怎麼實作。

百度了一通,說是要用到重力感應,也能百度到代碼,使用上吧,結果不太好使,大多是 cocos2d-x的代碼,用C++寫的。

于是由看看手冊,手冊裡就有啊。腳本開發指南--->玩家輸入事件

onload 如下代碼

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

    // 更新 scoreDisplay Label 的文字
    //this.scoreDisplay.string = 'Score: ' + this.score.toString() + event.acc.x + "   " + event.acc.y;
    //this.scoreDisplay.string = event.acc.x.toFixed(2);
    //cc.log(event.acc.x + "   " + event.acc.y);

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

    cc.log('nowGX:'+nowGX+'nowGY:'+nowGY+'nowGZ:'+nowGZ);
    this.scoreDisplay.string = parseFloat(event.acc.x.toFixed(2));
    var stand = 0.2;
    if((nowGX< -stand ||nowGX> stand )&&(nowGY<-stand||nowGY>stand) &&
        (nowGZ < -stand || nowGZ > stand))
    {
        this.score += 1;
        this.scoreDisplay.string = this.score.toString();
    }}
           

最開始的寫法,隻是簡單的比較判斷 下x,y 的值大小來 定義一次搖動,但是經測試有個問題, 手機傾斜到某些位置,score分數增加的很快,大概一秒兩三十次。明顯不對有問題,又是百度一兩小時,百度上沒有類似答案和算法。怎麼辦呢?不能在此耗費太多時間,是以接下來,我就開始别的内容開發。

就是。與後端怎麼通信?

未完待續。。。。。

繼續閱讀