Cocos2dx系列笔记3:牛刀小试->忍者飞镖射幽灵的Demo
就是这个例子,应该很简单,主要用到的有:精灵的移动,触摸,碰撞检测。
赶紧搞定,待会还要陪哲哲来几局爱消除。
首先在Scene初始化方法里添加精灵:
CCSprite *player =CCSprite::create("Player.png",CCRectMake(0,0,27,40));
player->setPosition(ccp(origin.x+ player->getContentSize().width/2,origin.y+visibleSize.height/2));
this->addChild(player,1);
注意,以前的版本初始化方法叫spriteWithFile
修改Scene背景色
class HelloWorld : public cocos2d::CCLayerColor
if ( !CCLayerColor::initWithColor(ccc4(255,255,255,255)) )
随机在屏幕右侧添加幽灵
void HelloWorld::addTarget()
{
CCSprite *target=CCSprite::create("Target.png",CCRectMake(0,0,27,40));
CCSize winSize=CCDirector::sharedDirector()->getWinSize();
int minY=target->getContentSize().height/2;
int maxY=winSize.height;
int rangeY=maxY-minY;
int acturalY=(rand()%rangeY)+minY;
target->setPosition(ccp(winSize.width-target->getContentSize().width/2,acturalY));
this->addChild(target);
}
初始化里调用addTarget几次,此时,屏幕上就应该有忍者和几个随机的幽灵了,
骨头忍不住在手机上跑下看看,注意,要拷贝新资源到assets里。
cocos2d-x中CCCallFunc CCCallFuncN CCCallFuncND的区别:差了下,就是参数区别
void callback1();
void callback2(CCNode* sender);
void callback3(CCNode* sender, void* data);
CCCallFunc::create(this, callfunc_selector(testCallFunc::callback1)),NULL);
CCCallFuncN::create(this, callfuncN_selector(testCallFunc::callback2)),NULL);
CCCallFuncND::create(this, callfuncND_selector(testCallFunc::callback3), (void*)0xbebabeba),NULL);
添加动作和事件监听
CCFiniteTimeAction *actionMove=CCMoveTo::create((float)actualD,ccp(100-target->getContentSize().width,winSize.height/2));
CCFiniteTimeAction* actionMoveDone = CCCallFuncN::create(this,callfuncN_selector(HelloWorld::spriteMoveFinished));
target->runAction(CCSequence::create(actionMove,actionMoveDone,NULL));
void HelloWorld::spriteMoveFinished(CCNode* sender)
{
CCSprite *sprite = (CCSprite *)sender;
this->removeChild(sprite);
CCLOG("Anim stop!");
addTarget();
}
每隔1秒调用一下
this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );
添加触摸事件
void ccTouchesEnded(cocos2d::CCSet *touches,cocos2d::CCEvent *event);
this->setTouchEnabled(true);
触摸事件里添加子弹,并且(move方法里)算出子弹的运行线路
CCSprite *bullet=CCSprite::create("Projectile.png",CCRectMake(0,0,20,20));
this->addChild(bullet,0,2);
this->move(bullet,location.x,location.y);
先了解下更新机制
scheduleUpdate();
schedule(schedule_selector(Updatedemo::update),1.0f);
scheduleOnce(schedule_selector(Updatedemo::update2),8.0f);
然后再用子弹遍历幽灵,判断两个矩形是否相交,即中弹
if (CCRect::CCRectIntersectsRect(projectileRect, targetRect))判断方法
中弹后,该remove的remove,该减分的减分。
笔记:
遍历CCArray
CCARRAY_FOREACH(array, object){}
类型转换,jt为CCObject,转换为CCSprite
CCSprite *target = dynamic_cast<CCSprite*>(jt);
//添加SimpleaudioEngine.h
#include "SimpleAudioEngine/SimpleAudioEngine.h"
//播放背景音乐的代码
SimpleAudioEngine::getSharedEngine()->playBackgroundMusic("background-music-aac.mp3");
//播放音效的代码
SimpleAudioEngine::getSharedEngine()->playEffect("pew-pew-lei.wav");
label赋值char
sprintf(buffer,"code: %i",res);
简单一记录,骨头去把这个demo完成了去
噼里啪啦%……×&×(
搞定,做成了霰弹效果,哲哲喊了,Z Z Z...