您的位置:首页 > 移动开发 > Cocos引擎

cocos2d-x SimpleGame(3)如何发射子弹

2013-01-12 18:29 330 查看
现在我们要让主角开枪干掉敌人,添加如下代码让图层支持触摸事件。

// 设置图层支持触摸事件
this->setTouchEnabled(true);

这样我们就可以接收到屏幕触摸事件了。

在HelloWorldScene.h声明屏幕触摸事件的回调函数

void ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
以及注册使Layer处理Touch事件

void registerWithTouchDispatcher();


在HelloWorldScene.cpp文件内进行实现

bool HelloWorld::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent )
{
// 获得点击屏幕的坐标
CCPoint location = pTouch->locationInView();
// 把坐标从屏幕坐标系转为OpenGL坐标系
location = CCDirector::sharedDirector()->convertToGL(location);

// 获得屏幕尺寸
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
// 获得子弹精灵
CCSprite *projectile = CCSprite::create("Projectile.png");
// 设置子弹的初始位置
projectile->setPosition( ccp(20, winSize.height/2) );

// 计算点击屏幕位置和子弹初始位置在X轴的距离和Y轴的距离
int offX = location.x - projectile->getPosition().x;
int offY = location.y - projectile->getPosition().y;

// 如果点击位置在子弹初始位置的左边则退出不显示子弹
if (offX <= 0) return true;

// 把子弹加入图层
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);

// 计算子弹飞出屏幕后的位置和子弹初始位置的距离,设置速度为480像素/秒
int offRealX = realX - projectile->getPosition().x;
int offRealY = realY - projectile->getPosition().y;
float length = sqrtf((offRealX * offRealX)
+ (offRealY*offRealY));
float velocity = 480/1; // 480pixels/1sec
// 计算子弹飞完整段路程所需时间
float realMoveDuration = length/velocity;

// 启动动画,动画完成后的回调函数是spriteMoveFinished(),我们已经实现过
projectile->runAction( CCSequence::actions(
CCMoveTo::create(realMoveDuration, realDest),
CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)),
NULL) );
return true;
}

void HelloWorld::registerWithTouchDispatcher()
{
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
}


OK,编译并运行,点击屏幕,试试效果



附本章源码下载:http://download.csdn.net/detail/lpkkk/4997331

文章所写的东西只是我自己的理解,如果哪里出现错误,敬请斧正。

您可以留言、微博私聊我或Email我

我的微博:http://weibo.com/u/2007282737

我的Email:pengkailiao@gmail.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: