天天看点

摇一摇诞生记三(手机重力传感事件)(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分数增加的很快,大概一秒两三十次。明显不对有问题,又是百度一两小时,百度上没有类似答案和算法。怎么办呢?不能在此耗费太多时间,所以接下来,我就开始别的内容开发。

就是。与后端怎么通信?

未完待续。。。。。

继续阅读