zoukankan      html  css  js  c++  java
  • [cocos2d-x] 让精灵响应触摸 并把方向旋转到相对应的角度

    在cocos2d-x里面  想要把一个精灵从原位置移动到用户所触摸到的点 , 并且把精灵的方向旋转相对应的弧度,可以参考一下我的做法

    我这里的精灵是用一条鱼, 用户触摸后鱼就移动到所触摸的点, 并且移动开始时鱼头的方向已经向着所触摸的点 下面是详细做法

    首先  h文件申明重写CCLayer里面的四个方法 :

     

        virtualvoid registerWithTouchDispatcher(void);

       virtualbool ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent);

       virtualvoid ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent);

       virtualvoid ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent);


    然后在cpp文件里面的init方法让当前图层实现触摸: 

    this->setTouchEnabled(true);


    接着在cpp文件里重写的方法实现:

     

    void StartGame::registerWithTouchDispatcher()
    {
        CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,INT_MIN-1,true);
    }
    bool StartGame::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {
        
        CCPoint p=pTouch->getLocation();
        CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);//根据tag获取我的精灵
        nowsprite->cocos2d::CCNode::setRotation(atan2((p.x-nowsprite->getPositionX()),(p.y-nowsprite->getPositionY()))*180/3.1415926+90);//改变弧度 后面加不加90要根据精灵的初始角度是怎样的
        CCMoveTo * move_ten =CCMoveTo::create(1, p); //设定移动所用的时间和坐标
        nowsprite->runAction(move_ten);
       return true;
    }
    
    void StartGame::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {
        CCPoint p=pTouch->getLocation();
        CCSprite * nowsprite=(CCSprite*)this->getChildByTag(888);
        nowsprite->setPosition(p);
    }
    void StartGame::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) 
    {
    //这里写结束触摸需要实现的功能
    }

     

    
    

  • 相关阅读:
    Discuz X3.2 分区 gid 完美伪静态方法 Apache/Nginx
    如何批量转换 WordPress 文章分类
    修改 WordPress 文件上传目录
    如何验证 jemalloc 优化 Nginx 是否生效
    .Net Core 1.1 + CentOs 7 环境配置
    DotNet Core中使用dapper
    爬虫 HttpHelper
    iTextSharp 不适用模板 代码拼接PDF
    .Net中的加密解密
    .Net Core使用 MiniProfiler 进行性能分析
  • 原文地址:https://www.cnblogs.com/riasky/p/3372066.html
Copyright © 2011-2022 走看看