Cocos2d 基础知识 2

这篇博客详细介绍了Cocos2d-X中处理单点触摸事件的方法,包括触摸开始、移动、结束和取消的事件监听器,并展示了如何注册和销毁这些监听器。此外,还提到了屏幕适配的策略,如EXACT_FIT、NO_BORDER、SHOW_ALL等,并讲解了如何使用Cocos2d-X的事件监听器进行多点触摸交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 单点触摸

//触摸开始

bool  Chapter05::onTouchBegan(Touch*touch,Event *unused_event)

//{

//    log("Touch Began\r\n");

//    Vec2 touchPoint =touch->getLocation();

//    log("x:%f,y%f",touchPoint.x,touchPoint.y);

//    return true;

//}

//触摸移动

// void  Chapter05::onTouchMoved(Touch*touch,Event *unused_event)

//{

//    auto drawNode=DrawNode::create();//创造 轨迹

//    this->addChild(drawNode,10);


//   Vec2 touchPoint =touch->getPreviousLocation();

//    log("Touch Moved\r\n");

//     log("x:%f,y%f",touchPoint.x,touchPoint.y);

//    if (sp->getBoundingBox().containsPoint(touch->getLocation()))//边界框  包含()

//    {

//        sp->setPosition(touch->getLocation());// 位置

////        drawNode->drawLine(touch->getLocation(), touch->getPreviousLocation(), Color4F(1, 0, 0, 1));

//    }

//    drawNode->drawLine(touch->getLocation(), touch->getPreviousLocation(), Color4F(1, 0, 0, 1));

//

//}

触摸结束


// void  Chapter05::onTouchEnded(Touch*touch,Event *unused_event)

//{

//    Vec2 touchPoint =touch->getStartLocation();

//    log("Touch Ended\r\n");

//

//}

触摸取消:例 手机出现了来电,是我们游戏进入后台

// void  Chapter05::onTouchCancelled(Touch*touch,Event *unused_event)

//{

//    long("Touch Cancelled\r\n");

//}



//单点触摸


onEnter()

{

/*//    auto touchListener=EventListenerTouchOneByOne::create();//触摸监听

//    touchListener->onTouchBegan=CC_CALLBACK_2(Chapter05::onTouchBegan, this);

//    touchListener->onTouchMoved=CC_CALLBACK_2(Chapter05::onTouchMoved, this);

//    touchListener->onTouchEnded=CC_CALLBACK_2(Chapter05::onTouchEnded, this);

//    touchListener->onTouchCancelled=CC_CALLBACK_2(Chapter05::onTouchCancelled, this);

//    

//  Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority (touchListener,this);//注册该监听

//    drawNode->drawLine(touch->getLocation(), touch->getPreviousLocation(), Color4F(1, 0, 0, 1));*/

}

在哪里注册就在哪里销毁,销毁触摸接听

void Chapter05::onExit()

{

    Director::getInstance()->getEventDispatcher()->removeEventListenersForTarget(this);

    Layer::onExit();

}

或者种形式

void ChaCase1::onEnter()

{

    Layer::onEnter();

    auto  touchListener = EventListenerTouchOneByOne::create();

    touchListener->onTouchBegan = CC_CALLBACK_2(ChaCase1::onTouchBegan,this);

    touchListener->onTouchMoved = CC_CALLBACK_2(ChaCase1::onTouchMoved,this);

    touchListener->onTouchEnded = CC_CALLBACK_2(ChaCase1::onTouchEnded, this);

    touchListener->onTouchCancelled=[=](Touch* t,Event * e)

    {

        Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);

    };

    touchListener->setSwallowTouches(true);

    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);

    

    

    this->scheduleUpdate();

}




//模态对话框

/* {

        auto visableSize = Director::getInstance()->getVisibleSize();

        auto sp = Sprite::create("StartBG.png");

        sp->setPosition(240,160);

        sp->setScale(sp->getContentSize().width/visableSize.width, sp->getContentSize().height/visableSize.height);

        this->addChild(sp);

        //

        //

        auto btn1 = Button::create("c0.png");

        btn1->setPosition(Vec2(240, 160));

        btn1->addClickEventListener([=](Ref* sender){

            cout<<"btn1"<<endl;

            

            

            auto widget = Widget::create();//创建一个widget对象 ,类似于一个层

            widget->setAnchorPoint(Vec2(0, 0));//设置锚点

            widget->setPosition(Vec2(0, 0));//设置位置

            widget->setContentSize(visableSize);//设置覆盖区域

            widget->setTouchEnabled(true);//开启触摸

            widget->setSwallowTouches(true);//吞噬触摸

            this->addChild(widget);

            

            

            auto sp1 = Sprite::create("tabBg1.png");

            sp1->setPosition(240,160);

            widget->addChild(sp1);

            

            

            auto _btn = Button::create("c4.png");

            _btn->setAnchorPoint(Vec2(1, 1));

            _btn->setPosition(sp1->getContentSize());

            _btn->addClickEventListener([=](Ref* sender){

                cout<<"_btn"<<endl;

                  //删除父节点中的当前节点并清除动作及回调函数

                widget->removeFromParentAndCleanup(true);

            });

            sp1->addChild(_btn);

            

            

        });

        this->addChild(btn1);

        

        

        auto btn2 = Button::create("c1.png");

        btn2->setPosition(Vec2(240, 220));

        btn2->addClickEventListener([=](Ref* sender){

            cout<<"btn2"<<endl;

        });

        this->addChild(btn2);

        

        

        

        auto btn3 = Button::create("c2.png");

        btn3->setPosition(Vec2(240, 100));

        btn3->addClickEventListener([=](Ref* sender){

            cout<<"btn3"<<endl;

        });

        this->addChild(btn3);

        

    }*/



//画轨迹

/*//    auto drawNode=DrawNode::create();//创造 轨迹

//    

//    this->addChild(drawNode,10);

//    drawNode->setLineWidth(10);//线宽

    //画路线

//    drawNode->drawLine(Vec2(0,0), Vec2(480,320), Color4F(1, 0, 0, 1));//画路线

//    //                 开始位置     结束位置           线颜色

//    //画圆

//    drawNode->drawCircle(Vec2(240,160), 50, 90, 4, false, Color4F(1, 0, 0, 1));//画圆


//    //画点

//    drawNode->drawDot(Vec2(50,50), 20, Color4F(0,0,0,1));

    

    //rect矩形

//    drawNode->drawRect(Vec2(visableSize.width/2-100,50), Vec2(visableSize.width/2+100,50), Vec2(visableSize.width/2+100,100), Vec2(visableSize.width/2-100, 100), Color4F(1,0,0,1));

    //

  //drawCubicBezier贝塞尔曲线

//    drawNode->drawCubicBezier(Vec2(0,origin.y), Vec2(visableSize.width/2,origin.y+visableSize.height/4), Vec2(visableSize.width/2,origin.y+visableSize.height*3/4), Vec2(visableSize.width, origin.y+visableSize.height), 100, Color4F(1,1,0,1));

    

    */


广告字幕循环

 auto text =Text::create ("!京北来迎欢","",40);

            text->setPosition(Vec2(240,160));

            this->addChild(text,1);

            auto moveby=MoveBy::create(6, Vec2(270,0 ));

    

    auto call = CallFunc::create([=](){

        text->setPosition(Vec2(0,160));

    });

    auto sequence = Sequence::create(moveby,call, NULL);

    auto rep = RepeatForever::create(sequence);

    text->runAction(rep);

    

    auto stencil=Sprite::create("fish_1.png");

    auto  clippingNode=ClippingNode::create();

    clippingNode->setStencil(stencil);//设置裁剪模板

    clippingNode->setInverted(true);//设置地板可见

    clippingNode->setAlphaThreshold(0);//设置绘制底板透明度为0

    clippingNode->setPosition(Vec2(240,160));

    this->addChild(clippingNode,2);

    

    auto content=Sprite::create("任务效果图.png");


    content->setScale(content->getContentSize().width/240, content->getContentSize().height/160);


    clippingNode->addChild(content,2);



多点触摸



void Chapter05::onEnter()

{

    

   

    Layer::onEnter();

    

    auto touchListener=EventListenerTouchAllAtOnce::create();

    touchListener->onTouchesBegan=CC_CALLBACK_2(Chapter05::onTouchesBegan,this );

    touchListener->onTouchesMoved=CC_CALLBACK_2(Chapter05::onTouchesMoved,this );

    touchListener->onTouchesEnded=CC_CALLBACK_2(Chapter05::onTouchesEnded,this );

    touchListener->onTouchesCancelled=CC_CALLBACK_2(Chapter05::onTouchesCancelled,this );


    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);

}


void Chapter05::onExit()

{

    Director::getInstance()->getEventDispatcher()->removeEventListenersForTarget(this);

    Layer::onExit();

}


void Chapter05::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event)

{

    

    log("\r\nTouches began\r\n");

    for (auto item:touches)

    {

        log("x=%f,y=%f",item->getLocation().x,item->getLocation().y);

    }

    if(touches.size()>1)

    {

        auto a1=touches[0]->getLocation();

        auto a2=touches[1]->getLocation();

        distance=a1.distance(a2);

    }

    

}

void Chapter05::onTouchesMoved(const std::vector<Touch*>& touches, Event *unused_event)

{

    log("\r\nTouches began\r\n");

    for(auto item:touches)

    {

        log("x=%f,y=%f",item->getLocation().x,item->getLocation().y);

    }

    

    if(touches.size()>1)

    {

        auto a11=touches[0]->getLocation();

        auto a12=touches[1]->getLocation();

        float _distance=a11.distance(a12);//两点的距离

        float _scale=_distance/distance;

    

       if (_scale>=10)

        {

         _scale=10;

        }

    sp->setScale( _scale);

    }

    

}

void Chapter05::onTouchesEnded(const std::vector<Touch*>& touches, Event *unused_event)

{

    log("\r\nTouches began\r\n");

    for(auto item:touches)

    {

        log("x=%f,y=%f",item->getLocation().x,item->getLocation().y);

    }

}

void Chapter05::onTouchesCancelled(const std::vector<Touch*>& touches, Event *unused_event)

{

    log("\r\ntouches cancellde\r\n");

}





      






删除之前动作


  auto _callfunc=CallFunc::create([=](){

//removeFromParentAndCleanup

表示把sprite从屏幕上删除

           

 //删除父节点中的当前节点并清除动作及回调函数

            progressCircle1->removeFromParentAndCleanup(true);

        });

    //一样的功能,删除

    //        auto _callfunc=RemoveSelf::create();


    this->removeChild(text);





弧长=nπr/180,在这里n就是角度数,即圆心角n所对应的弧长。


n=弧度/ π*180       n就是角度数

atan();求弧度的函数



    Vec2 touchPoint=touch->getPreviousLocation();


    float tan;

    float angle;

    if (touchPoint.x>=240)

    {

        tan=touchPoint.y/(touchPoint.x-240);

        angle=90-atan(tan)/3.14*180;

        s666->setRotation(angle);

    }

    if (touchPoint.x<240)

    {

        tan=touchPoint.y/(240-touchPoint.x);

        angle=270+atan(tan)/3.14*180;

        s666->setRotation(angle);

    }

float CatchFish1::cannonRotation(Point p1,Point p2)//大炮旋转 p1是鼠标位置   p2是大炮位置

{

    float offx=p1.x-p2.x;

    float offy=p1.y-p2.y;

    if (offy<=0)

    {

        return -180;

    }

    

    float ratio= offy/ offx;

    float angle=atan(ratio)/M_PI*180;

    if (angle>0) {

        cannon->setRotation(90-angle);

        

        return 90-angle;

    }

    else

    {

        cannon->setRotation(-90-angle);

        return -90+angle;

    }

    

    

}








static Color4F color=Color4F::BLUE;

layer1=LayerColor::create(Color4B::WHITE,300,200);

btn3->setScale9Enabled(true);



碰撞框


   bool containsPoint(const CCPoint& point) const;
    bool intersectsRect(const CCRect& rect) const;


         Vec2 PerPoint=touch->getPreviousLocation();//

        Vec2 touchPoint=touch->getLocation();//当前点

          碰撞的图片                                                   鼠标当前点

        if (layer1->getBoundingBox().containsPoint(touchPoint))

        {

            drawNode->drawLine(PerPoint, touchPoint, color);

        }

   //矩形与矩形的碰撞检测

   auto fishNetRect = fishNet->getBoundingBox();

       

   auto fishRect = fish->getBoundingBox();


   fishNetRect.intersectsRect(fishRect))//相交的矩形





 //粒子效果气泡

    auto bubble=ParticleSystemQuad::create("qipaom.plist");

    bubble->setPosition(Vec2(240, 100));

    bubble->setAutoRemoveOnFinish(true);//是否在结束后自动删除

    bubble->setEmissionRate(5);//每秒 5个

    bubble->setDuration(-1);//循环

    this->addChild( bubble,4);












第7章屏幕适配




屏幕适配  第一个参数 设计分辨率宽 高 适配策略


  setDesignResolutionSize(DW, DH, resolutionPolicy)



资源分辨率,设计分辨率,屏幕分辨率

 

Resources width 以下简写为RW, Resources height 以下简写为RH

Design width 以下简写为DW,       Design height 以下简写为DH

Screen width 以下简写为SW,       Screen height 以下简写为SH

例如:



    EXACT_FIT:屏幕宽 与 设计宽比 作为X方向的缩放因子,屏幕高 与 设计高比 作为Y方向的缩放因子。保证了设计区域完全铺满屏幕,但是可能会出现图像拉伸


    NO_BORDER:屏幕宽、高分别和设计分辨率宽、高计算缩放因子,取较(大)者作为宽、高的缩放因子。保证了设计区域总能一个方向上铺满屏幕,而另一个方向一般会超出屏幕区域


    SHOW_ALL:屏幕宽、高分别和设计分辨率宽、高计算缩放因子,取较(小)者作为宽、高的缩放因子。保证了设计区域全部显示到屏幕上,但可能会有黑边


    FIXED_HEIGHT:保持传入的设计分辨率高度不变,根据屏幕分辨率修正设计分辨率的宽度。


    FIXED_WIDTH:保持传入的设计分辨率宽度不变,根据屏幕分辨率修正设计分辨率的高度。






#include "cocostudio/CocoStudio.h"

#include "ui/CocosGUI.h"

using namespace cocos2d::ui;



 

    auto root=CSLoader::createNode("Layer.csb");

    this->addChild(root);



AppDelegate.cpp里面写                               文件夹

 FileUtils::getInstance()->addSearchPath(“COCOSSTUDIO");

作用是写图片:不用加COCOSSTUDIO/

新设置的路径放在路径搜索的前面


MessageBox 写2个参数  提示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值