關於cocos2dx裡面的重力感應事件

2021-07-03 23:22:07 字數 2337 閱讀 6356

這次這個只是我學習的乙個記錄,重力感應就像touch事件一樣,我們在init裡面開啟重力感應事件,然後重寫函式就可以了。

首先在init裡面開啟重力事件:

this->setaccelerometerenabled(true);//開啟重力感應

this->setkeypadenabled(true);//這個是開啟手機的返回鍵事件,大家可以忽略這個

現在我們重寫函式:

//重力感應事件

virtual void didaccelerate(ccacceleration* paccelerationvalue);

//返回按鈕,大家可以忽略

virtual void keybackclicked();

相應函式的重寫:

螢幕的巨集:

#define fix_pos(_pos, _min, _max) \

if (_pos < _min)        \

_pos = _min;        \

else if (_pos > _max)   \

_pos = _max;  

bool helloworld::init()

ccsize visiblesize= ccdirector::shareddirector()->getvisiblesize();

cclabelttf *lable= cclabelttf::create("helloworld","arial",34);

lable->setposition(ccp(visiblesize.width/2,visiblesize.height-50));

this->addchild(lable,0,0);

ccsprite *psprite= ccsprite::create("closenormal.png");

psprite->setposition(ccp(visiblesize.width/2,visiblesize.height/2));

this->addchild(psprite,0,1);

this->setaccelerometerenabled(true);//開啟重力感應

this->setkeypadenabled(true);

return true;

}void helloworld::didaccelerate(ccacceleration* paccelerationvalue)

cclabelttf *lable=(cclabelttf*)pobjectlable;

std::ostringstream strstream;//輸出相應的x,y,z

strstream<<"x:"std::string str=strstream.str();

lable->setstring(str.c_str());

//改變小球位置

ccobject *pobjectsprite= this->getchildbytag(1);

if (pobjectsprite==null)

ccsprite *psprite=(ccsprite*)pobjectsprite;

ccsize pspritesize= psprite->getcontentsize();

ccpoint ptnow  = psprite->getposition();

ccpoint pttemp=ccdirector::shareddirector()->converttoui(ptnow);

pttemp.x += paccelerationvalue->x * 9.81f;

pttemp.y -= paccelerationvalue->y * 9.81f;

ccpoint ptnext = ccdirector::shareddirector()->converttogl(pttemp);

ccsize visiblesize= ccdirector::shareddirector()->getvisiblesize();

fix_pos(ptnext.x, (pspritesize.width / 2.0), (visiblesize.width - pspritesize.width / 2.0));

fix_pos(ptnext.y, (pspritesize.height / 2.0), (visiblesize.height - pspritesize.height / 2.0));

psprite->setposition(ptnext);

}void helloworld::keybackclicked()//可以忽略

我們的功能主要是建立了乙個小球,然後發布在手機上就可以看見相應的效果。

大家輕噴

----------蛋蛋

關於cocos2dx中tableView的一些理解

先看 h檔案中 ifndef helloworld scene h define helloworld scene h include cocos2d.h include cocos ext.h using ns cc using ns cc ext class helloworld public ...

cocos2dx筆記 關於action

1.基本動作instantaction 放置 place 隱藏 hide 顯示 show 可見切換 togglevisibility 2.延時動作 移動到 ccmoveto 移動 ccmoveby 跳躍到 ccjumpto 跳躍 ccjumpby 貝塞爾 ccbezierby 放大到 ccscale...

關於學習cocos2d x的計畫

學習cocos2d x才一段時間,對cocos2d x基本概念,以及它開發遊戲的過程基本上有了個總體的把握。由於自己用在win32下用gdi寫過小遊戲,加上看過一些關於遊戲程式設計的書籍,所以對遊戲方面有相應的了解。因此看起cocos2d x的書籍基本上都能很快理解。但是同時,由於看得過快,總是很多...