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. 《Linux命令行大全》系列(三、Linux 系统)

    在<Linux命令行大全>一书中,第3章名称是 Linux 系统. 概念太大,不过该节内容却是 Linux 系统最为核心的基础——查看 Linux 系统. ls 命令 显示目录自身信息或目 ...

  2. Codeforces Round #197 (Div. 2) : E

    看了codeforces上的大神写的题解之后,才知道这道题水的根本! 不过相对前面两题来说,这道题的思维要难一点: 不过想到了水的根本,这题也真心不难: 方法嘛,就像剥洋葱一样,从外面往里面剥: 所以 ...

  3. [译]GotW #2: Temporary Objects

        不必要的和(或)临时的变量经常是罪魁祸首,它让你在程序性能方面的努力功亏一篑.如何才能识别出它们然后避免它们呢? Problem JG Question: 1. 什么是临时变量? Guru Q ...

  4. B*tree dump

    Oracle的索引是以平衡树的方式组织存储的:保存的是索引列的值,以及该行的rowid的一部分(文件号,块号,行号) 下面我们通过例子来了解一下: 1,create table test(id int ...

  5. java学习之多生产者和多消费者

    在上一节当中我们说道了,java多线程当中单个消费者对应单个生产者的关系.这个时候有几个点需要注意一下,第一个就是把if判断flag的语句改成while这样能够避免,比如如果我们这个时候用if的话判断 ...

  6. hadoop2.2编程:序列化

    测试序列化后的长度 提示:需要用到的类,以及继承关系如下: 1.java.lang.Object |__ java.io.OutputStream |__ java.io.ByteArrayOutpu ...

  7. POJ_3181_Dollar_Dayz_(动态规划,完全部分和,完全背包)

    描述   http://poj.org/problem?id=3181 FJ有n元钱,有k种商品,各为1,2,...,k-1,k元,问有多少种花掉这n元钱的方法. Dollar Dayz Time L ...

  8. Android——监听开机启动,自启动应用程序

    1.首先继承一个broadcastreceiver public class ConnectBroadCastReceiver extends BroadcastReceiver { @Overrid ...

  9. HDJ -- 1022

    #include<iostream> #include<cstdio> #include<string> #define MAXN 10 using namespa ...

  10. Lua 中使用面向对象(续)

    上一篇文章给了一个面向对象的方案,美中不足的是没有析构函数 Destructor,那么这一次就给它加上. 既然是析构,那么就是在对象被销毁之前做该做的事情,lua 5.1 的 userdata 可以给 ...