cocos2d简单弹球

今天我们介绍如何用cocos2d/Box2d实现一个简单的弹球程序:点击屏幕会新生成一个小球,在下落过程中碰到其他球或墙壁则会反弹。

1.

新建一个cocos2d/Box2d Application,输入名称Ball:

2.

修改HelloWorldLayer.h如下:

#import "cocos2d.h"
#import "Box2D.h"// HelloWorldLayer
@interface HelloWorldLayer : CCLayer
{CGSize _screenSize;b2World * _world;b2Body * _groundBody;
}+(CCScene *)scene;
-(void)initWorld;
-(void)addBall:(CGPoint)p;
-(void)showLabel:(NSString *)str fontName:(NSString *)name fontSize:(int)size position:(CGPoint)pos rgb:(ccColor3B)color;@end

函数功能不解释了,看名字就知道了。

3.

修改HelloWorldLayer.mm如下:

#import "HelloWorldLayer.h"#define PTM_RATIO 32// HelloWorldLayer implementation
@implementation HelloWorldLayer+(CCScene *)scene
{CCScene * scene = [CCScene node];HelloWorldLayer * layer = [HelloWorldLayer node];[scene addChild: layer];return scene;
}-(id)init
{if( (self=[super init])){// Enable touchesself.isTouchEnabled = YES;_screenSize = [CCDirector sharedDirector].winSize;CCLOG(@"Width: %0.2f, Height: %0.2f", _screenSize.width, _screenSize.height);// Init the world[self initWorld];//Create the sprite[self addBall:CGPointMake((int)(_screenSize.width / 2), (int)(_screenSize.height / 2))];//Show label[self showLabel:@"Tap screen" fontName:@"Marker Felt" fontSize:32 position:ccp(_screenSize.width/2, _screenSize.height-50) rgb:ccc3(0,0,255)];[self schedule: @selector(tick:)];}return self;
}-(void)initWorld
{// Create the worldb2Vec2 gravity;gravity.Set(0.0f, -10.0f);bool doSleep = true;_world = new b2World(gravity, doSleep);_world->SetContinuousPhysics(true);// Create the groundb2BodyDef groundBodyDef;groundBodyDef.position.Set(0,0);_groundBody = _world->CreateBody(&groundBodyDef);b2PolygonShape groundBox;b2FixtureDef groundBoxDef;groundBoxDef.shape = &groundBox;groundBox.SetAsEdge(b2Vec2(0, 0), b2Vec2(_screenSize.width / PTM_RATIO, 0));_groundBody->CreateFixture(&groundBoxDef);groundBox.SetAsEdge(b2Vec2(0, 0), b2Vec2(0, _screenSize.height / PTM_RATIO));_groundBody->CreateFixture(&groundBoxDef);groundBox.SetAsEdge(b2Vec2(0, _screenSize.height / PTM_RATIO), b2Vec2(_screenSize.width / PTM_RATIO, _screenSize.height / PTM_RATIO));_groundBody->CreateFixture(&groundBoxDef);groundBox.SetAsEdge(b2Vec2(_screenSize.width / PTM_RATIO, _screenSize.height / PTM_RATIO), b2Vec2(_screenSize.width / PTM_RATIO, 0));_groundBody->CreateFixture(&groundBoxDef);
}// Init the world
-(void)addBall:(CGPoint)p
{CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);//Create the spriteCCSprite * ballSprite = [CCSprite spriteWithFile:@"Ball.jpg" rect:CGRectMake(0, 0, 52, 52)];ballSprite.position = p;ballSprite.tag = 1;[self addChild:ballSprite];// Create ball body b2BodyDef ballBodyDef;ballBodyDef.type = b2_dynamicBody;ballBodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO);ballBodyDef.userData = ballSprite;b2Body * ballBody = _world->CreateBody(&ballBodyDef);// Create circle shapeb2CircleShape circle;circle.m_radius = 26.0 / PTM_RATIO;// Create shape definition and add to bodyb2FixtureDef ballShapeDef;ballShapeDef.shape = &circle;ballShapeDef.density = 1.0f;ballShapeDef.friction = 0.0f;ballShapeDef.restitution = 0.8f;ballBody->CreateFixture(&ballShapeDef);
}-(void)showLabel:(NSString *)str fontName:(NSString *)name fontSize:(int)size position:(CGPoint)pos rgb:(ccColor3B)color
{CCLabelTTF * label = [CCLabelTTF labelWithString:str fontName:name fontSize:size];[self addChild:label z:0];[label setColor:color];label.position = pos;
}-(void)tick: (ccTime) dt
{//It is recommended that a fixed time step is used with Box2D for stability//of the simulation, however, we are using a variable time step here.//You need to make an informed choice, the following URL is useful//http://gafferongames.com/game-physics/fix-your-timestep/int32 velocityIterations = 8;int32 positionIterations = 1;// Instruct the world to perform a single step of simulation. It is// generally best to keep the time step and iterations fixed._world->Step(dt, velocityIterations, positionIterations);//Iterate over the bodies in the physics worldfor (b2Body * b = _world->GetBodyList(); b; b = b->GetNext()){if (b->GetUserData() != NULL){CCLOG(@"X: %0.2f, Y: %02.f",b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);//Synchronize the AtlasSprites position and rotation with the corresponding bodyCCSprite * myActor = (CCSprite *)b->GetUserData();myActor.position = CGPointMake(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());}}
}- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{//Add a new body/atlas sprite at the touched locationfor(UITouch * touch in touches){CGPoint location = [touch locationInView: [touch view]];location = [[CCDirector sharedDirector] convertToGL: location];[self addBall:location];}
}- (void)dealloc
{delete _world;_world = NULL;// don't forget to call "super dealloc"[super dealloc];
}
@end

在init函数中:

self.isTouchEnabled = YES;

表示启用触摸:在触摸开始时会自动调用 ccTouch(es)Began函数,在触摸结束时会自动调用ccTouch(es)Ended函数,在其中我们调用addBall函数创建一个球。


之后我们创建了一个重力为10,垂直向下的World,并在屏幕的四周创建了四面墙壁。


然后我们调用addBall创建一个球:

首先我们创建了一个sprite(精灵),之后创建了一个b2Body,然后用userData将它们绑定起来,方便我们之后获取它。


在init函数的最后我们调用了:

[self schedule: @selector(tick:)];

表示每一帧后都会调用tick函数,而在tick函数中,我们一个一个遍历World中的b2Body,一旦userData不空,我们就把它转为sprite,然后根据b2Body的坐标设置sprite的坐标。



因此可以总结如下:

我们创建了一个cocos2d中的sprite和一个Box2d中的b2Body。sprite通过spriteWithFile函数载入图片,因此可见;b2Body不可见,但它的运动遵循物理定律,因此在b2Body每运动一帧后我们都根据它的坐标设置sprite的坐标,这样看上去就像是这个sprite按物理定律运动一样。

好了,程序很简单,

结果如下:

最后我把代码也上传上来了:

http://download.csdn.net/detail/htttw/4464843

完成!

cocos2d简单弹球相关推荐

  1. Scratch 简单弹球游戏

    [项目演示] 完成此游戏的所有资料已经整理好,如图: 所有资料下载链接: Scratch 简单弹球游戏

  2. 弹球小程序怎么用c语言编写,C语言实现简单弹球游戏

    电视机待机的屏幕上的弹球,怎么实现? 今天文章就跟大家分享下C语言实现简单弹球游戏的具体代码,供大家参考,具体内容如下 #include #include #include #include #inc ...

  3. java简单弹球游戏

    package chapter11;import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util ...

  4. cocos2d 简单高仿天天酷跑游戏

    1.先直接上视频来看下这个游戏的样子(GIF已经不能满足这个游戏的展示了) 跑酷游戏最纠结的是地图,碰撞倒是简单,可以自己写或者使用box2d等物理引擎.跑酷游戏地图的特点就是随机性.但是随机中又有策 ...

  5. cocos2d 简单消除游戏算法 (一)

    1. 游戏视频演示 2.三消游戏我的理解 上面视频中的游戏,我做了2个星期时间,只能算个简单Demo,还有bug,特效也几乎没有.感觉三消游戏主要靠磨,越磨越精品.市场上三消游戏已经超级多了.主流的是 ...

  6. JAVA_AWT 实现简单弹球小游戏

    学习AWT中的绘图功能的小案例:教程位置:这里 package com.lzy.pinballgame;import java.awt.*; import java.awt.event.*;/*** ...

  7. python小游戏开发——简单弹球游戏

    一家懂得用细节留住客户的3年潮牌老店我必须支持!➕

  8. cocos2d 高仿doodle jump 无源代码

    1. 游戏视频 主角眼熟吗?没错,上次跑酷游戏中的"30"来Jump了,有三种道具.主角光环,竹蜻蜓.翅膀: 有两种怪物,螃蟹和鸟: 有5种板子.点击屏幕,30会把它的嘴巴3给发射 ...

  9. cocos2d 高仿doodle jump 无源码

    1. 游戏视频 主角眼熟吗?没错,上次跑酷游戏中的"30"来Jump了,有三种道具,主角光环,竹蜻蜓,翅膀: 有两种怪物,螃蟹和鸟: 有5种板子.点击屏幕,30会把它的嘴巴3给发射 ...

  10. 简易弹球游戏 (2)

    简单弹球游戏 一.小游戏功能描述 功能一:进入小游戏界面,点击play,游戏开始,点击exit可继续上一局游戏. 功能二:小球和球拍分别以圆形区域和矩形区域代替,小球开始以随机速度向下运动,遇到上方的 ...

最新文章

  1. 基于Windows配置COLMAP环境
  2. 帧率配置_《骑马与砍杀2》配置探究:CPU显卡怎么搭配达到理想画质和帧数?...
  3. 安卓和ios抓包神器
  4. 网络主机监控-nagios应用漫谈(三)
  5. mysql57 修改root密码,MySQL 5.7.x修改root默认密码(CentOS下)
  6. 《Head First 设计模式》ch.3 装饰(Decorator)模式
  7. 用JS写的取存款功能
  8. ubuntu切换root用户
  9. 【翻译】Test-After Development is not Test-Driven Development
  10. 微信用户量破6.5亿 首超移动QQ
  11. Spring3 报org.aopalliance.intercept.MethodInterceptor问题解决方法
  12. innodb_rollback_on_timeout
  13. EasyRecovery用法进阶--高阶设置使用技巧
  14. linux 远程修改时间,linux 获取远程系统时间的例子
  15. 职业规划范文500字计算机专业,技校计算机专业职业生涯规划500字左右
  16. python读取cad元素_python3读取autocad图形文件.py实例
  17. ectouch v1 thinkphp的搜索问题
  18. Kaptcha 使用
  19. 编制职工档案管理程序C语言,职工档案管理系统
  20. 百度天眼android,百度天眼下载|百度天眼安卓版 v1.2.0.20423_手机天堂

热门文章

  1. 2021金融科技领域最具商业合作价值企业盘点
  2. 4245. 【五校联考6day2】er
  3. 项目使用微信公众平台图片显示此图片来自微信公众平台 解决方法
  4. function里面的两个参数是什么意思?
  5. 软件混沌工程原则以及应用介绍(PRINCIPLES OF CHAOS ENGINEERING)
  6. 高射炮打蚊子丨在VS 2017里用C语言写经典的冒泡排序
  7. vm服务器虚拟机如何导出报表,教程:浏览 VM 中的 Power BI 报表服务器 - Power BI | Microsoft Docs...
  8. 反病毒工具-PEiD
  9. 计算机图形学入门(十七)-光线追踪(蒙特卡洛积分与路径追踪)
  10. LabVIEW自动整理程序框图