Chapter 5 - How to Detect the Collisions

Our hero can fire bullets now, but the bullets are only visual. So how can they kill their enemies?

In this chapter, we will introduce Collision Detection to implement it.

Firstly, it’s necessary to track the enemies and the bullets.

In the game, we add a tag for these two kinds of sprites to identify them. Let tag = 1 if the sprite is an enemy, and tag = 2 mean it is a bullet. Because CCSprite inherits from CCNode, there is already a member variable m_nTag with methods setTag() and getTag(); we can implement this to identify the different types of sprites.

Add the two member variables below to HelloWorld in HelloWorldScene.h. These are used to store the existing enemies and bullets.

1// cpp with cocos2d-x
2protected:
3 cocos2d::CCArray *_targets;
4 cocos2d::CCArray *_projectiles;

In cocos2d-x, CCMutableArray is an implementation of NSMutableArray in iOS which contains NSObject's and their subclasses. Something different is that you should specify the concrete category of its members.

Then initialize the two variables in the construct function, new them in init(), and release them in the destruct function.

 1// cpp with cocos2d-x
2
3// in init()
4// Initialize arrays
5_targets = new CCArray;
6_projectiles = new CCArray;
7
8HelloWorld::~HelloWorld()
9{
10 if (_targets)
11 {
12 _targets->release();
13 _targets = NULL;
14 }
15
16 if (_projectiles)
17 {
18 _projectiles->release();
19 _projectiles = NULL;
20 }
21
22 // cpp don't need to call super dealloc
23 // virtual destructor will do this
24}
25
26HelloWorld::HelloWorld()
27:_targets(NULL)
28,_projectiles(NULL)
29{
30}

Now modify addTarget() to add a new target to targets array, and set its tag to be 1.

1// cpp with cocos2d-x
2// Add to targets array
3target->setTag(1);
4_targets->addObject(target);

Modify ccTouchesEnded() to add a new bullet to bullets array, and set its tag to be 2.

1// cpp with cocos2d-x
2// Add to projectiles array
3projectile->setTag(2);
4_projectiles->addObject(projectile);

Then, modify spriteMoveFinished() as follows. Here we remove the sprites from their corresponding arrays.

 1// cpp with cocos2d-x
2void HelloWorld::spriteMoveFinished(CCNode* sender)
3{
4 CCSprite *sprite = (CCSprite *)sender;
5 this->removeChild(sprite, true);
6
7 if (sprite->getTag() == 1) // target
8 {
9 _targets->removeObject(sprite);
10 }
11 else if (sprite->getTag() == 2) // projectile
12 {
13 _projectiles->removeObject(sprite);
14 }
15}

The function update() below is used to detect collisions every frame, remove the collided bullet and enemy from the scene.
Declare it in HelloWorldScene.h and Define it in HelloWorldScene.cpp.

 1// cpp with cocos2d-x
2void HelloWorld::update(float dt)
3{
4 CCArray *projectilesToDelete = new CCArray;
5 CCArray* targetsToDelete =new CCArray;
6 CCObject* it = NULL;
7 CCObject* jt = NULL;
8
9 CCARRAY_FOREACH(_bullet, it)
10 {
11 CCSprite *projectile = dynamic_cast<CCSprite*>(it);
12 CCRect projectileRect = CCRectMake(
13 projectile->getPosition().x - (projectile->getContentSize().width/2),
14 projectile->getPosition().y - (projectile->getContentSize().height/2),
15 projectile->getContentSize().width,
16 projectile->getContentSize().height);
17
18 CCARRAY_FOREACH(_target, jt)
19 {
20 CCSprite *target = dynamic_cast<CCSprite*>(jt);
21 CCRect targetRect = CCRectMake(
22 target->getPosition().x - (target->getContentSize().width/2),
23 target->getPosition().y - (target->getContentSize().height/2),
24 target->getContentSize().width,
25 target->getContentSize().height);
26
27 if (projectileRect.intersectsRect(targetRect))
28 {
29 targetsToDelete->addObject(target);
30 projectilesToDelete->addObject(projectile);
31 }
32 }
33 }
34
35 CCARRAY_FOREACH(targetsToDelete, jt)
36 {
37 CCSprite *target = dynamic_cast<CCSprite*>(jt);
38 _target->removeObject(target);
39 this->removeChild(target, true);
40 }
41
42 CCARRAY_FOREACH(projectilesToDelete, it)
43 {
44 CCSprite* projectile = dynamic_cast<CCSprite*>(it);
45 _bullet->removeObject(projectile);
46 this->removeChild(projectile, true);
47 }
48
49 projectilesToDelete->release();
50 targetsToDelete->release();
51}

Ok, the last thing we should do is adding update() to the schedule to let it be called every frame.

1// cpp with cocos2d-x
2this->schedule( schedule_selector(HelloWorld::update) );

Compile and run the project, fire the bullets as you like, then: AH..AH.., the enemies are killed one by one.

Chapter 5 - How to Detect the Collisions的更多相关文章

  1. js实现四叉树算法

    最近在看canvas动画方面教程,里面提到了采用四叉树检测碰撞.之前也看到过四叉树这个名词,但是一直不是很懂.于是就又找了一些四叉树方面的资料看了看,做个笔记,就算日后忘了,也可以回来看看. Quad ...

  2. [译]2D空间中使用四叉树Quadtree进行碰撞检测优化

    操作系统:Windows8.1 显卡:Nivida GTX965M 开发工具:Unity2017.2.0f3 原文出处 : Quick Tip: Use Quadtrees to Detect Lik ...

  3. [转]第四章 使用OpenCV探测来至运动的结构——Chapter 4:Exploring Structure from Motion Using OpenCV

    仅供参考,还未运行程序,理解部分有误,请参考英文原版. 绿色部分非文章内容,是个人理解. 转载请注明:http://blog.csdn.net/raby_gyl/article/details/174 ...

  4. JavaScript- The Good Parts CHAPTER 2

    I know it well:I read it in the grammar long ago.—William Shakespeare, The Tragedy(悲剧:灾难:惨案) of Titu ...

  5. JavaScript- The Good Parts Chapter 6

    Thee(你) I’ll chase(追逐:追捕) hence(因此:今后), thou(你:尔,汝) wolf in sheep’s array.—William Shakespeare, The ...

  6. JavaScript- The Good Parts Chapter 4

    Why, every fault’s condemn’d ere it be done:Mine were the very cipher of a function. . .—William Sha ...

  7. MongoDB:The Definitive Guide CHAPTER 2 Getting Started

    MongoDB is very powerful, but it is still easy to get started with. In this chapter we’ll introduce ...

  8. Notes : <Hands-on ML with Sklearn & TF> Chapter 1

    <Hands-on ML with Sklearn & TF> Chapter 1 what is ml from experience E with respect to som ...

  9. JVM Specification 9th Edition (4) Chapter 3. Compiling for the Java Virtual Machine

    Chapter 3. Compiling for the Java Virtual Machine 内容列表 3.1. Format of Examples 3.2. Use of Constants ...

随机推荐

  1. redis百度百科和维基百科知识总结:

    1. 百度百科知识总结: Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis ...

  2. [原博客] POJ 2484 A Funny Game

    题目链接题意:有n个硬币排成一圈,两个人轮流操作,每次可以取走一个或者相邻的连个硬币(只算最开始相邻的,取之后才相邻的不算),问先手必胜还是必败. 这个题可以证明若n>=3,则先手必败.对称博弈 ...

  3. Tomcat J2ee 发布步骤

    1.找到要发布的工程,并发布到本地tomcat下,测试完全没有问题,找到tomcat下webapps下 并找到该工程,进入该工程目录,全选添加到  drivingSchool.zip 或  drivi ...

  4. ASP.NET MVC4 UEditor 的上传图片配置路径

    ASP.NET MV4下,使用UEditor1.4.3最新版本,网址就不说了,去百度官网下载即可,关于在Controler下如何配置,直接上图: 然后再Views下面来个页面引用如下:     < ...

  5. 【HDOJ】2149 Public Sale

    看Discuss说是博弈论,没学到这个分类.不过仔细想了想,发现.如果m<=n,那么可能结果为m,m+1...n.否则,如果m%(n+1) == 0,那么无论如何都会输,因为无论先报价什么数,如 ...

  6. .NET混淆工具 (Dotfuscator Professional Edition)

      如果不想自己辛辛苦苦码出来的作品被人轻易的破解cpoy就使用这款工具试试吧.^_^   使用版本:4.9.7500.9484 ,破解版:http://pan.baidu.com/s/1dDH7lr ...

  7. Java---俄罗斯方块小游戏

    去年就已经学了这个技术了,一直没去写,现在抽个时间写了个俄罗斯方块游戏. 只有简单的新游戏,暂停,继续,积分功能.简单的实现了俄罗斯的经典功能. 不介绍了,有兴趣的自己运行一下,后面贴出了图片. 代码 ...

  8. bzoj 2618 2618: [Cqoi2006]凸多边形(半平面交)

    2618: [Cqoi2006]凸多边形 Time Limit: 5 Sec  Memory Limit: 128 MBSubmit: 656  Solved: 340[Submit][Status] ...

  9. JavaScript高级程序设计35.pdf

    遍历 “DOM2级遍历和范围”模块定义了两个用于辅助完成顺序遍历DOM结构的类型:NodeIterator和TreeWalker,两个类型能够基于给定的起点对DOM结构执行深度优先(depth-fir ...

  10. (转载)利用burp suite截断上传拿shell

    burpsuite上传必须要有filepath这个参数 第一步:选择一个jpg后缀的马. 第二步:设置本地代理,burp的本地端口是8080 第三步:打开burp suite 按图操作就ok了. 第四 ...