Hi,敌人一直向小黑侠进攻,为什么小黑侠不发动攻击呢?
哈哈,当然是我们还没做呢,今天我们就来让小黑侠发射子弹罗,呼呼,开始罗
首先我们的 HelloWorld是继承CCLayerColor,而CCLayerColor又继承CCLayer,OK
我们需要的效果的点哪里,子弹就往哪里打,很容易就想到我们要开启CCLayer的触摸,
看代码如下:
再次说明下 cocos2d-x 1.x this->setIsTouchEnabled(true);
而 cocos2d-x 2.x this->setTouchEnabled(true);
//设置接受触摸 this->setTouchEnabled(true);
这样我们就能接受到touch event的了。
在HelloWorldScene.h里声明回调函数“void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);”,并在HelloWorldScene.cpp实现这个函数。
接下来看代码:
//************* //Touch Method //************* //触摸结束 void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event) { CCTouch* touch = (CCTouch*)(touches->anyObject()); CCPoint location = touch->getLocationInView(); location = CCDirector::sharedDirector()->convertToGL(location); //转为opengl坐标 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSprite* projectile = CCSprite::create("Projectile.png",CCRectMake(0,0,20,20)); projectile->setPosition(ccp(20,winSize.height/2)); //计算飞镖的偏移 // Determinie offset of location to projectile int offX = location.x - projectile->getPosition().x; int offY = location.y - projectile->getPosition().y; if (offX<=0) return; this->addChild(projectile); //计算飞镖该哪个方向飞 // Determine where we wish to shoot the projectile to 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); //计算可以飞多远 // Determine the length of how far we're shooting int offRealX = realX - projectile->getPosition().x; int offRealY = realY - projectile->getPosition().y; float length = sqrtf((offRealX * offRealX) + (offRealY * offRealY)); float velocity = 480/1; float realMoveDuration = length/velocity; //移动Action // Move projectile to actual endpoint projectile->runAction(CCSequence::create( CCMoveTo::create(realMoveDuration, realDest), CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)),NULL)); }
好了,编译并运行,哈哈,开始发子弹了啊,希望大家相互学习,有不对可以指出。