功能:玩家点击屏幕的时候,主角往点击位置的方向发射飞镖
首先需要使游戏能够接受触屏事件
在HelloWorld::init()中加入
this->setTouchEnabled(true);
接下来就是处理触屏事件了,在触屏事件中加入发射飞镖的动作
在HelloWorld.h头文件中加入声明
// 触屏回调函数
void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
在HelloWorld.cpp中实现
1// cpp with cocos2d-x
2void HelloWorld::ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event)
3{
4 // Choose one of the touches to work with
5 CCTouch* touch = (CCTouch*)( touches->anyObject() );
6 CCPoint location = touch->locationInView();
7 location = CCDirector::sharedDirector()->convertToGL(location);
8
9 // Set up initial location of projectile
10 CCSize winSize = CCDirector::sharedDirector()->getWinSize();
11 CCSprite *projectile = CCSprite::create("Projectile.png",
12 CCRectMake(0, 0, 20, 20));
13 projectile->setPosition( ccp(20, winSize.height/2) );
14
15 // Determinie offset of location to projectile
16 int offX = location.x - projectile->getPosition().x;
17 int offY = location.y - projectile->getPosition().y;
18
19 // Bail out if we are shooting down or backwards
20 if (offX <= 0) return;
21
22 // Ok to add now - we've double checked position
23 this->addChild(projectile);
24
25 // Determine where we wish to shoot the projectile to
26 int realX = winSize.width
27 + (projectile->getContentSize().width/2);
28 float ratio = (float)offY / (float)offX;
29 int realY = (realX * ratio) + projectile->getPosition().y;
30 CCPoint realDest = ccp(realX, realY);
31
32 // Determine the length of how far we're shooting
33 int offRealX = realX - projectile->getPosition().x;
34 int offRealY = realY - projectile->getPosition().y;
35 float length = sqrtf((offRealX * offRealX)
36 + (offRealY*offRealY));
37 float velocity = 480/1; // 480pixels/1sec
38 float realMoveDuration = length/velocity;
39
40 // Move projectile to actual endpoint
41 projectile->runAction( CCSequence::create(
42 CCMoveTo::create(realMoveDuration, realDest),
43 CCCallFuncN::create(this,
44
45 callfuncN_selector(HelloWorld::spriteMoveFinished)),
46 NULL) );
47}
运行一下,点击屏幕,主角真的发射飞镖了