第四步:让主角Player发射飞镖

功能:玩家点击屏幕的时候,主角往点击位置的方向发射飞镖


首先需要使游戏能够接受触屏事件

在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}
运行一下,点击屏幕,主角真的发射飞镖了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wudics

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值