本文没你想象的那么,,复杂。事实上就是通过重力感应控制个小球移动而已。
先看头文件:
- #ifndef __HELLOWORLD_SCENE_H__
- #define __HELLOWORLD_SCENE_H__
-
- #include "cocos2d.h"
- USING_NS_CC;
-
- class HelloWorld : public cocos2d::CCLayer
- {
- public:
- HelloWorld(void);
- ~HelloWorld(void);
-
-
- virtual bool init();
-
-
- static cocos2d::CCScene* scene();
-
-
- void menuCloseCallback(CCObject* pSender);
-
- virtual void didAccelerate(CCAcceleration* pAccelerationValue);
-
-
- CREATE_FUNC(HelloWorld);
-
- protected:
- CCSprite* m_pBall;
- double m_fLastTime;
- };
-
- #endif // __HELLOWORLD_SCENE_H__
看.cpp
- #include "HelloWorldScene.h"
-
- using namespace cocos2d;
-
- #define FIX_POS(_pos, _min, _max) \
- if (_pos < _min) \
- _pos = _min; \
- else if (_pos > _max) \
- _pos = _max; \
-
- HelloWorld::HelloWorld()
- : m_fLastTime(0.0)
- {
- }
-
- HelloWorld::~HelloWorld()
- {
- m_pBall->release();
- }
-
- CCScene* HelloWorld::scene()
- {
- CCScene * scene = NULL;
- do
- {
-
- scene = CCScene::create();
- CC_BREAK_IF(! scene);
-
-
- HelloWorld *layer = HelloWorld::create();
- CC_BREAK_IF(! layer);
-
-
- scene->addChild(layer);
- } while (0);
-
-
- return scene;
- }
-
-
- bool HelloWorld::init()
- {
- bool bRet = false;
- do
- {
- CC_BREAK_IF(! CCLayer::init());
-
- CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
- "CloseNormal.png",
- "CloseSelected.png",
- this,
- menu_selector(HelloWorld::menuCloseCallback));
- CC_BREAK_IF(! pCloseItem);
-
-
- pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
-
-
- CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
- pMenu->setPosition(CCPointZero);
- CC_BREAK_IF(! pMenu);
-
-
- this->addChild(pMenu, 1);
-
-
- CSize size = CCDirector::sharedDirector()->getWinSize();
-
- setAccelerometerEnabled(true);
-
- m_pBall = CCSprite::create("ball.png");
- m_pBall->setPosition(ccp(size.width/2, size.height/2));
- addChild(m_pBall);
-
- m_pBall->retain();
-
- bRet = true;
- } while (0);
-
- return bRet;
- }
-
- <pre name="code" class="cpp">void HelloWorld::menuCloseCallback(CCObject* pSender)
- {
-
- CCDirector::sharedDirector()->end();
- }
-
- void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
- {
-
-
-
-
-
-
-
-
- CCSize size = CCDirector::sharedDirector()->getWinSize();
-
- CCDirector* pDir = CCDirector::sharedDirector();
-
-
- if ( m_pBall == NULL ) {
- return;
- }
-
- CCSize ballSize = m_pBall->getContentSize();
-
- CCPoint ptNow = m_pBall->getPosition();
- CCPoint ptTemp = pDir->convertToUI(ptNow);
-
-
- ptTemp.x += pAccelerationValue->x * 9.81f;
- ptTemp.y -= pAccelerationValue->y * 9.81f;
-
- CCPoint ptNext = pDir->convertToGL(ptTemp);
- FIX_POS(ptNext.x, (0+ballSize.width / 2.0), (size.width - ballSize.width / 2.0));
- FIX_POS(ptNext.y, (0+ballSize.height / 2.0), (size.height - ballSize.height / 2.0));
- m_pBall->setPosition(ptNext);
- }</pre>
- <p></p>
- <pre></pre>