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

现在我们要让主角开枪干掉敌人,添加如下代码让图层支持触摸事件。

// 设置图层支持触摸事件
		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


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值