cocos2d-x 2.X demo学习笔记 6 ----ClickAndMoveTest 触摸事件和移动

    setTouchEnabled(true);  //设置允许接收触摸事件
    
    CCSprite* sprite = CCSprite::create(s_pPathGrossini);//创建精灵
    
    CCLayer* layer = CCLayerColor::create(ccc4(255,255,0,255));//创建一个布局,并设置颜色
    addChild(layer, -1);//添加布局,并设置id
        
    addChild(sprite, 0, kTagSprite);//添加精灵并设置id
    sprite->setPosition( CCPointMake(20,150) );//设置初始位置
    
    sprite->runAction( CCJumpTo::create(4, CCPointMake(300,48), 100, 4) );//设置动作跳跃到
    
    layer->runAction( CCRepeatForever::create( 
                                                        (CCActionInterval*)( CCSequence::create(    
                                                                            CCFadeIn::create(1),
                                                                            CCFadeOut::create(1),
                                                                            NULL) )

                                                        ) ); //设置背景图的渐隐渐现

void MainLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{//触摸事件
    CCSetIterator it = pTouches->begin();//获取触摸事件对象
    CCTouch* touch = (CCTouch*)(*it);
    
    CCPoint location = touch->getLocation();//获取点击的位置


    CCNode* s = getChildByTag(kTagSprite);//通过id获取角色对象
    s->stopAllActions();//停止该角色所有当前动作
    s->runAction( CCMoveTo::create(1, CCPointMake(location.x, location.y) ) );//运行移动到被点击的位置
    float o = location.x - s->getPosition().x;//
    float a = location.y - s->getPosition().y;
    float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); //反切值。可以做塔防游戏时炮口方向使用,旋转精灵的方向,CC_RADIANS_TO_DEGREES宏的意思是转换成度数
    
    if( a < 0 ) 
    {
        if(  o < 0 )
            at = 180 + fabs(at);
        else
            at = 180 - fabs(at);    //求浮点数x的绝对值
    }
    
    s->runAction( CCRotateTo::create(1, at) );//旋转到,第二个参数是角度
}

abs是针对整数的求绝对值

fabs是针对浮点数



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值