Chapter4 – 如何放出子弹
好嘛现在有妖怪来了,主人公要有一些技能干掉他们。鉴于objc和C++的区别已经有了一些详细的介绍,这章里也并没有什么新的情况发生,我就不抄objc的代码了,直接只上C++。
首先我们要让它听玩家指挥,在 HelloWorld::init 方法中添加这一行。
// cpp with cocos2d-x this->setTouchEnabled(true);
这样我们就能接受到触摸屏幕的消息了,其实在win32平台上,是鼠标点击事件……
然后在HelloWorldScene.h声明一下响应事件的回调函数
void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
然后在HelloWorldScene.cpp实现它:
// cpp with cocos2d-x void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { // 从触摸点的集合中选取一个点 CCTouch* touch = (CCTouch*)( touches->anyObject() ); CCPoint location = touch->getLocation(); // 初始化你的飞镖并且设定一个起点 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSprite *projectile = CCSprite::create("Projectile.png", CCRectMake(0, 0, 20, 20)); projectile->setPosition( ccp(20, winSize.height/2) ); // 计算以下飞镖起点相对于我们触摸点的X、Y坐标的偏移量 int offX = location.x - projectile->getPosition().x; int offY = location.y - projectile->getPosition().y; // 我们要往有妖怪的地方打……所以往后打飞镖我们不放出来 /* 不用担心这里return了之前create的飞镖没有释放会造成 内存泄漏,使用create方法产生的对象都是自动释放的, 除非你曾经手动的调用了它的 retain() 方法。*/ if (offX <= 0) return; // 既然它朝着妖怪打,那么就把它加到游戏层里去 this->addChild(projectile); // 计算一下飞镖最终的目的地,我们希望它飞出屏幕再消失 int realX = winSize.width + (projectile->getContentSize().width/2); float ratio = (float)offY / (float)offX; int realY = (realX * ratio) + projectile->getPosition().y; CCPoint realDest = ccp(realX, realY); // 计算一下飞镖要飞多远,因为速度是相同的,要来计算它的时间。 int offRealX = realX - projectile->getPosition().x; int offRealY = realY - projectile->getPosition().y; float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY)); float velocity = 480/1; // 480 速度是 pixel/ 1 second float realMoveDuration = length/velocity; // 用MoveTO动作让飞镖用同样的速度飞到不同的目的地,同样执行结束 // 之后用调用 spriteMoveFinished 方法。 projectile->runAction( CCSequence::create( CCMoveTo::create(realMoveDuration, realDest), CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)), NULL) ); }
好了,生成跑一遍。在窗口上点鼠标看看效果吧。