cocos2d-x 动态背景

本文介绍如何使用Cocos2d-x游戏引擎搭建基本的游戏场景,包括背景的滚动效果、游戏角色的添加及触控事件处理等。通过具体代码示例展示了游戏场景的基本构成要素及其交互方式。

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

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

    //添加背景

   CCSprite *spritebackground=CCSprite::create("background4.png");

    spritebackground->setTag(100);

   this->addChild(spritebackground);

    spritebackground->setAnchorPoint(ccp(0,0));//设置背景坐标原点为(00

   CCSprite *spritebackground2=CCSprite::create("background4.png");

    spritebackground2->setTag(101);

   this->addChild(spritebackground2);

    spritebackground2->setAnchorPoint(ccp(0,0));

    spritebackground2->setPositionY(spritebackground->getContentSize().height);

    //添加怪物

    

    //添加飞机

   CCSprite *spriteplane=CCSprite::create("player.png");

    spriteplane->setTag(102);

   this->addChild(spriteplane);

    spriteplane->setPosition(ccp(160,100));

    //定义纹理对象

   CCTexture2D *texture;

    texture=CCTextureCache::sharedTextureCache()->addImage("player.png");

    //获取飞机的尺寸

//    float spriteW=spriteplane->getContentSize().width/4;

//    float spriteH=spriteplane->getContentSize().height;

    //创建飞机的动画

    CCAnimation *animation=CCAnimation::create();

    animation->setDelayPerUnit(0.1f);//设置动画得播放间隔时间

   for (int i=0; i<4; i++)

        animation->addSpriteFrameWithTexture(texture,CCRectMake(i*48,0, 58, 56));

  

    //让飞机图层执行动画化动作

    spriteplane->runAction(CCRepeatForever::create(CCAnimate::create(animation)));

    

    this->schedule(schedule_selector(GameScence::moveBackground),0.03);


  return true;

}

voidGameScence::registerWithTouchDispatcher(void){

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,1, false);

}

boolGameScence::ccTouchBegan(CCTouch *pTouch,CCEvent *pEvent)

{

    return true;

}

voidGameScence::ccTouchMoved(CCTouch *pTouch,CCEvent *pEvent)

{

   CCPoint p=pTouch->getLocation();

   CCSprite *spritep=(CCSprite *)this->getChildByTag(102);

    spritep->setPosition(p);

}

voidGameScence::ccTouchEnded(CCTouch *pTouch,CCEvent *pEvent){

    

}

voidGameScence::moveBackground(float t)

{

    //移动背景   得到背景

   CCSprite *spriteback=(CCSprite *)this->getActionByTag(100);

   spriteback->setPositionY(spriteback->getPositionY()-1);

   CCSprite *spriteback2=(CCSprite *)this->getChildByTag(101);

    spriteback2->setPositionY(spriteback2->getPositionY()-1);

   if (spriteback->getPositionY()<-(spriteback->getContentSize().height)) {

        spriteback->setPositionY(0);

        spriteback2->setPositionY(spriteback->getContentSize().height);

    }

    

}

cocos2d::CCScene* GameScence::scene(){

   CCScene *scene=CCScene::create();

    GameScence *layer=GameScence::create();

    scene->addChild(layer);

   return scene;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值