天天看點

iphone遊戲開發之cocos2d ( 八 )使用加速計(重力感應)控制精靈移動UIAcceleration

holydancer原創,如需轉載,請在顯要位置注明:

轉自holydancer的CSDN專欄,專欄位址:http://blog.csdn.net/holydancer

上次我們實作了一個不停運動的精靈(一個不停搖尾巴的小魚),今天我們來嘗試用重力感應控制這個小魚的遊動,通過搖擺傾斜手上的裝置(模拟器不行,像GPS,加速計這些都需要硬體支援的,你懂的),來控制精靈的遊動,像好多賽車遊戲,都需要用到這種技術;

首先需要強調的是ios裝置上,包括大部分裝置上的加速計都是支援三軸立體感應的,我們将iphone螢幕向上放到桌上,那麼z軸上的力就是-1g,如果豎着放(home鍵在下)那麼Y軸上的力就是-1g;g是機關,我們在應用中調用的一般都是純粹的符點數字,甩一甩或者搖一下的話,那麼作用在某一個方向上的力就會突然加大,力度不同,值也不同,一般情況下絕對值會在1.5左右;另外在cocos2d中,隻需要開啟加速計支援,不需要再額外設定delegate,該層就可以直接調用-(void)accelerometer: didAccelerate:方法來擷取加速計返的數值;

核心方法有兩個:

-(void)update:(ccTime)delta

//用來根據傳回不同的加速計值來更新精靈的位置;

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

//用來讀取加速計傳回的值并設定一下靈敏度之類;

在IntroLayer.h中設定一個

 CGPoint posChange,用來根據加速計傳回的力值來做出不同的精靈移動速率;

在IntroLayer.m中開啟加速計功能,我們的操作要在該層上進行,是以該層要響應加速計方法;

layer.isAccelerometerEnabled=YES;

在IntroLayer.m中添加一個加速計方法

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    posChange.x = posChange.x *0.4f+ acceleration.x *7.0f;
    posChange.y = posChange.y *0.4f+ acceleration.y *7.0f;
//    CCLOG(@"acceleration.x = %f,acceleration.y = %f,posChange.x=%f,posChange.y =%f ",acceleration.x,acceleration.y,posChange.x,posChange.y);
    if (posChange.x>100) {
        posChange.x=100;
    }
    if (posChange.x<-100) {
        posChange.x=-100;
    }
    if (posChange.y>100) {
        posChange.y=100;
    }
    if (posChange.y<-100) {
        posChange.y=-100;
    }
}
           

其中acceleration.x,acceleration.y分别是在x軸和y軸上的力,有正負之分,代表中左右上下的不同傾斜,acceleration.z我們用不到,這裡不考慮;

其中

posChange.x = posChange.x *0.4f+ acceleration.x *7.0f;這個計算是為了将傳回的不同方向的值轉化為每幀精靈移動的距離,0.4和7.0大家可以随意做更改,一般可以多做幾次嘗試來調試出合适的參數,賽車遊戲中不同車的操控感也是因為這個算法不同引起的;
           

然後實作update方法,實作每幀畫面的變化;

-(void)update:(ccTime)delta

{

    CCSprite *sprite = (CCSprite *)[self getChildByTag:1];

    CGPoint pos = [self getChildByTag:1].position;

    pos.y -= posChange.x;

    //因為坐标系的原因,這裡要做下反向處理;

    //該項目我是預設的橫屏的,是以精靈的位置坐标是以左下角為原點的;

    pos.x += posChange.y;

    //下面是用來使精靈不至于飛到界面外;

    if (pos.x>1024) {

    //我用的是ipad,是以分辨率為1024 x 768

        pos.x = 1024;

        posChange.x = 0;

        posChange.y = 0;

    }

    if (pos.x<0) {

        pos.x = 0;

        posChange.x = 0;

        posChange.y = 0;

    }

    if (pos.y>768) {

        pos.y = 768;

        posChange.x = 0;

        posChange.y = 0;

    }

    if (pos.y<0) {

        pos.y = 0;

        posChange.x = 0;

        posChange.y = 0;

    }

    [self getChildByTag:1].position = pos;

    CCLOG(@"pos.x = %f,pos.y = %f,sprite.content.size.width=%f",pos.x,pos.y,sprite.contentSize.width);

//用來跟蹤精靈的坐标;

}

最後在該層的onEnter方法中記得調用

  [selfscheduleUpdate];

現在在真機上可以看出效果了;另外今天的代碼是在上次的基礎上實作的,是以有的地方描述的不夠詳細,主要是記錄一下思路,代碼比較粗糙,大家将就看吧;