ClickAndMoveTest

时间:2024-04-29 15:15:27

关于ccTouchesEnded看这个博客即可

http://blog.linguofeng.com/archive/2012/09/12/cocos2d-x-touch.html

class ClickAndMoveTestScene : public TestScene
{
public:
virtual void runThisTest();
}; class MainLayer : public CCLayer
{
public:
MainLayer();
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
};
void ClickAndMoveTestScene::runThisTest()
{
//创建目标图层
CCLayer* pLayer = new MainLayer();
pLayer->autorelease();
//添加图层
addChild(pLayer);
//替换场景,让改场景为运行时场景
CCDirector::sharedDirector()->replaceScene(this);
}
//目标图层类的构造函数
MainLayer::MainLayer()
{
//开启多点触控
setTouchEnabled(true); CCSprite* sprite = CCSprite::create(s_pPathGrossini);
//设置背景颜色
CCLayer* layer = CCLayerColor::create(ccc4(,,,));
addChild(layer, -); addChild(sprite, , kTagSprite);
sprite->setPosition( ccp(,) );
//对精灵做动作,这里精灵和背景层不在同一树种
sprite->runAction( CCJumpTo::create(, ccp(,), , ) );
//对背景层做动作,1.淡进,2.淡出,重复执行这两个动作
layer->runAction( CCRepeatForever::create(
(CCActionInterval*)( CCSequence::create(
CCFadeIn::create(),
CCFadeOut::create(),
NULL) )
) );
}
//处理松开事件
void MainLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
//获取第一个点
CCSetIterator it = pTouches->begin();
CCTouch* touch = (CCTouch*)(*it); CCPoint location = touch->getLocation(); CCNode* s = getChildByTag(kTagSprite);
//停止所有动作
s->stopAllActions();
//向该点移动
s->runAction( CCMoveTo::create(, ccp(location.x, location.y) ) );
//计算精灵的旋转角度,要让头部向着移动方向
float o = location.x - s->getPosition().x;
float a = location.y - s->getPosition().y;
//先通过atoanf 计算出反正弦弧度值,然后通过宏转换成角度值
float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) );
//在Cocos2D-x中,顺时针为正,逆时针为负
if( a < )
{
if( o < )
at = + fabs(at);//为什么这里是180在纸上画一下就明白了
else
at = - fabs(at);
}
//执行旋转动作
s->runAction( CCRotateTo::create(, at) );
}