游戏邦在:
杂志专栏:
gamerboom.com订阅到鲜果订阅到抓虾google reader订阅到有道订阅到QQ邮箱订阅到帮看

使用Cocos2D和Box2D制作《Jetpack Joyride》(1)

发布时间:2012-03-13 09:47:12 Tags:,,,

作者:Bogdan Vladu

在本系列教程中,我们将使用Cocos2D和Box2D来制作一款类似于《Jetpack Joyride》的游戏。

如果你还没有玩过《Jetpack Joyride》,你应该先试玩下,这是款相当精致有趣的游戏,而且是免费的!

Jetpack Joyride from raywenderlich.com

Jetpack Joyride from raywenderlich.com

你可以单单使用Cocos2D来制作这款游戏,但这需要花费大量的时间。为简化开发过程,我们将在下文中介绍使用两个工具:LevelHelper和SpriteHelper。

如果你对这两个工具不甚熟悉,以下是简单的介绍:

1、LevelHelper是个让关卡制作更加简单的工具。你只需要将精灵拖放到场景上即可!

2、SpriteHelper是个可用来简单快捷地为游戏制作精灵层和物理形状的工具。

我们将要制作的是个复杂的游戏,要做的事情很多,所以本系列教程将分为4个部分。本文是第1部分,我们要先花点时间来设置LevelHelper。然后,我们将制作一个带有持续视差滚动的基本关卡,学习如何使用SpriteHelper来添加和修改艺术。

到本系列教程结束时,你不仅将获得使用这些工具的宝贵经验,而且还会得到令人兴奋的高端游戏!

本教程假设你已经对Cocos2D和Box2D较为熟悉。如果你不熟悉这两个游戏框架,你应当先查看Cocos2D和Box2D的相关教程。

开始

首先,你需要下载下列内容:

1、LevelHelper和SpriteHelper

2、游戏所需的艺术,由Vicki Wenderlich制作

3、LevelHelper的Xcode 4模板

注:LevelHelper支持最新版Box2D,但Cocos2D中整合的是旧版Box2D。使用LevelHelper模板会使你的开发更加容易,因为它预整合了最新版Box2D。如果你想要使用普通Cocos2D模板,自行整合最新版Box2D,可以查看官方LevelHelper Cocos2D/Box2D Documentation中的指导。

安装LevelHelper模板

首先,确保你已经安装了Cocos2D 1.X模板(游戏邦注:不是Cocos2D 2.X)。如果你已安装的是Cocos2D 2.X模板,需要从Cocos2D下载页面下载1.X模板,然后重新安装模板。如果你以后需要使用Cocos2D 2.X模板,你可以再次重新安装。

接下来,解压Cocos2dBox2dXCode4Template.zip。你将看到如下文件夹结构:

templateFolderStructure

templateFolderStructure

点击桌面空白处,显示菜单栏。在菜单栏中选择“前往”:

go Menu 1

go Menu 1

在“前往”菜单显示时,按住Option(游戏邦注:或Alt)键,这样就能看到“库”文件夹。很好用的技巧,不是吗?点击继续。

现在,你应当可以看到电脑上的“库”文件夹。“库”的路径为/(你的电脑名)/用户/(你的用户名)/库。

go Menu Option Key

go Menu Option Key

现在,导航至Developer/XCode/Templates/Cocos2D。将解压Cocos2dBox2dXcode4Template.zip文件所得的两个文件夹复制到这个文件夹中。

所得文件夹结构应当如下图所示:

copy Folders In Cocos2d

copy Folders In Cocos2d

这样就表示你已经成功安装模板!让我们来尝试下这个模板。

copied Folders

copied Folders

创建Xcode项目

打开Xcode,从主菜单中选择“文件\新建\新项目”。

xcode New

xcode New

选择“iOS\cocos2d\LevelHelper_With_Cocos2d_And_Box2d”模板,点击“下一步”。

choose XCode Template

choose XCode Template

在接下来的对话框中,将你的项目命名为“RocketMouse”(游戏邦注:不含空格),再次点击“下一步”。

Name Rocket Mouse

Name Rocket Mouse

编译运行项目,你就会看到用LevelHelper制成的范例关卡:

Level Helper Sample

Level Helper Sample

不久之后,你就会知道自行创建这些关卡是件很容易的事情!

清除不需要的内容

我们从这里就可以开始扩展模板代码,但是为了让你更好地理解具体的运转方式,我们将从头开始。

首先,我们要先从模板代码中清除所有不需要的东西,分为两个步骤:清除资源和清除代码。

阅读下面的内容,自行清除代码。如果你不想这么做,也可以跳过这些步骤,直接下载已经清除完成的项目。

1、清除资源

在Xcode中导航至“资源”文件夹,选择位于“图片”和“关卡”文件夹中的所有文件。

all Files

all Files

现在,点击右键选择“删除”。

delete Files

delete Files

在弹出窗口中,选择“删除”。

delete Popup

delete Popup

2、清除代码

导航并点击HelloWorldScene.h,删除“b2MouseJoint* mouseJoint”这一行;

delete Header Code

delete Header Code

现在,导航并点击HelloWorldScene.mm。在初始化方法中,删除评论代码和通知代码,这两个代码我们都不需要。

commented Code And Notif

commented Code And Notif

删除用来移除通知的方法。

notif Methods Removed

notif Methods Removed

删除所有触碰方法的内容。

touch 1

touch 1

touch 2

touch 2

touch 3

touch 3

删除加速计代码。

accelerometer

accelerometer

最后,从dealloc方法中删除关节鼠释放代码:

delete DeallocJoint

delete DeallocJoint

注:此时项目可以编译,但是运行时会看到错误提示,因为没有可加载的关卡。别担心,我们马上就会创建一个关卡!

检查已清除代码

如果你查看HelloWorldScene.m,你会发现那里还残存些许代码。这段代码的作用是创建Box2D世界,设置Box2D调试图纸,在更新循环中运行Box2D模拟,更新精灵使之与相关Box2D实体相符。

在初始化中,还包含些许LevelHelper设置代码:

lh = [[LevelHelperLoader alloc] initWithContentOfFile:@”bezierTile”];

//creating the objects
[lh addObjectsToWorld:world cocos2dLayer:self];

if([lh hasPhysicBoundaries])
[lh createPhysicBoundaries:world];

if(![lh isGravityZero])
[lh createGravity:world];

首行代码用初始关卡来初始化LevelHelper。接下来数行使得LevelHelper可以向Box2D世界中添加对象以及根据关卡设置创建物理界限和万有引力。

花点时间浏览HelloWorldScene.mm,确保你理解其中的基本想法。我们将从这里开始游戏的构建!

准备LevelHelper

让我们在Xcode项目“资源”文件夹中创建两个新文件夹。事实上我们并不需要这么做,但保持项目组织结构完善会让我们接下来的工作更加容易!

在取景器中导航至Xcode项目,打开“资源”文件夹,创建两个名为“图片”和“关卡”的子文件夹。重点:在取景器中创建这些文件夹,而不是Xcode!

结果应当如下图所示:

resource Folders

resource Folders

创建LevelHelper项目

现在,项目设置完成,我们可以用LevelHelper来开始关卡的制作!

从版本1.4开始,LevelHelper将保持项目中内容的条理性。这意味着,关卡文件属于项目的一部分,而不是像以往那样是单独的文件。

那么,让我们用LevelHelper来创建新项目。将它打开,选择“文件\新项目”:

LH New Project

LH New Project

屏幕上会出现新的层窗口。在“项目名称”区域,输入“RocketMouse”,这便是我们项目的名称。“屏幕大小”保持默认值“iPhone Landscape (480×320)”。

注:如果你希望游戏能够支持所有iPhone和iPad型号,可以选择兼有横向或纵向的iPhone选项。LevelHelper会自动在iPhone2G/3G/3GS上使用SD,在iPhone4/4S和iPad1/iPad2上使用HD。

如果你希望游戏只适用于iPad,可以使用iPad模板,在SpriteHelper中创建精灵层时去除“保存SD”选项。

在iPad中,还有个不延伸图像的选项。这个选项不适用于本教程,因为我们将使用持续视差滚动。

在“SpriteHelper场景和图片文件目录”下,选择你刚刚在“资源”文件夹中创建的“图片”文件夹,点击“打开”。

LHSelect Images Folder

LHSelect Images Folder

在“源代码路径”下,从RocketMouse项目文件夹中选择“RocketMouse”文件夹。这个文件夹中包含“LevelHelper”文件夹。点击“打开”。

LH CodeFolder

LH CodeFolder

这个设置告诉LevelHelper要在何处自动生成代码。

在“引擎”下选择“Cocos2d With Box2d”。你选择的是希望LevelHelper自动为你生成的代码。在这个教程中,我们将使用带有Cocos2d With Box2d,但是你可以看到LevelHelper也支持其他多种引擎和配置。

确保“需要时自动生成代码”选项已选定。这就等同于告诉LevelHelper在代码更新时或向项目添加新便签后自动生成代码。

LHCodeSetting

LHCodeSetting

在“LevelHelper场景目录”下,选择你刚刚在“资源”文件夹中创建的“关卡”文件夹,点击“打开”。

LHSelectLevelsFolder

LHSelectLevelsFolder

最终,“项目”设置窗口应当如下图所示:

LHProjectSettings

LHProjectSettings

注:LevelHelper中的每项主功能旁都有个“?”按钮。点击可以观看解释该功能的视频。

接下来,点击“创建新项目”按钮。屏幕上会出现新窗口,让你将项目保存成文件。

将新文件保存在与Xcode项目相同的文件夹中。

LHSaveProject

LHSaveProject

现在,LevelHelper窗口应该如下图所示:

emptyProject

emptyProject

但是,我们还没有图片,窗口中什么都没有!该是开始添加艺术内容的时候了。

向LevelHelper项目添加艺术元素

如果要添加艺术,我们需要使用SpriteHelper,所以先将它打开。

接下来,导航到本教程所使用的艺术包的存放处。选择以下截图中所显示那些文件(游戏邦注:不是选择所有文件,只选择那些被选中的文件),将它们拖动到SpriteHelper中。

dragImagesInSh1

dragImagesInSh1

在右侧的层编辑器窗口中,取消“剪裁”选项的选定。“剪裁”会移除精灵上的透明空间,但是在某些动画中,精灵需要使用到透明度,所以我们不希望编辑器对透明度做出修改。

对于动画制作来说,取消“剪裁”选项总是项较好的选择。

接下来,点击层编辑器窗口底部的“打包精灵”按钮。

unselectCropAndPack 1

unselectCropAndPack 1

结果场景应该会与下图类似(游戏邦注:精灵的打包可能会有所不同):

将场景保存到“资源”文件夹中的“图片”文件夹中。选择“文件\保存为”。

SHResult 1

SHResult 1

在“保存”对话窗口中,将场景命名为“对象”,点击“保存”。

SHSaveAs

SHSaveAs

如果你现在查看LevelHelper窗口,你会看到艺术已经自动添加完成。

SaveAsImagesName

SaveAsImagesName

LevelHelper会跟踪“关卡”和“图片”文件夹中发生的所有变化,就像我们在创建项目时告知它一样。你每次添加、移除或修改这些文件夹中的文件,LevelHelper都会自动更新其内容。

LHUpdatesContent

LHUpdatesContent

注:如果你没有在LevelHelper中看到艺术内容,点击位于项目设置上方的栏目,查看“图片”文件夹的路径是否正确或者是否含有空格。

创建基础关卡

我们先来创建带有滚动地板和墙纸背景的关卡。

首先,我们要创建一个从右向左移动的持续视差滚动。要实现这个目前,就需要确定视差的大小。你可以根据自己的需要来设置。

让我们来将游戏世界的大小设为8个屏幕。点击“游戏世界大小”按钮。

PressGameWorldSize

PressGameWorldSize

在“宽度”空格中,输入3840,数值来源于8X480(游戏邦注:iPhone屏幕的宽度)。

gwWidth

gwWidth

现在,让我们来创建背景。将“bg”精灵拖动到关卡中,放置在首个屏幕的起始点。首个屏幕应当是位于左侧,红色边界所示区域。

dragFirstSprite

dragFirstSprite

现在,我们要复制精灵,这样它才能够覆盖所有的屏幕。选中背景精灵,在图片下方将克隆方向设置为右侧。

然后点击绿色的“+”标志。这便是克隆按钮。继续点击该按钮,直到背景精灵覆盖全部8个屏幕即可。

注:在LevelHelper中,拖动关卡时你可以按住ctrl来滚动关卡,滚动鼠标滚轴可以缩放关卡视图。

cloneSpriteWithDirection

cloneSpriteWithDirection

结果如下图所示:

clonedBackground

clonedBackground

让我们将这些图片添加到持续视差滚动中。导航至“视差”标签(游戏邦注:显示字幕“P”的标签),点击“新视差”按钮。

navigateToParallaxAndCreateNew

navigateToParallaxAndCreateNew

在选中视差时,勾选“持续滚动”选项。现在,选择关卡中所有的背景精灵,点击视差版块中的“添加已选场景精灵”按钮。

addSpritesToParallax

addSpritesToParallax

对于我们的持续视差滚动,我们还需要进行些许调整。首先,将“速度”预设为2.5(游戏邦注:随后将根据鼠标的移动速度来更改这项数值)。确保“方向”设定为“从右到左”。

现在,选择视差列表中的所有精灵,将“移动比率”设为“1”和“0”。这个比率和速度决定了精灵移动通过视差的速率。

setupParallax

setupParallax

在现在这种情况下,精灵的移动速率为1*2.5(游戏邦注:即比率*速度)。如果我们想要让其他精灵以不同的速率移动,可以对比率进行相应的修改(游戏邦注:比如0.4*2.5)。

如果你现在运行“场景测试器”,它就会移动持续视差!

runSceneTester

runSceneTester

保存这个关卡,将其在我们的Xcode项目中运行。在LevelHelper中,选择“文件\保存关卡为”。

saveFirstLevel

saveFirstLevel

在对话框中,输入“level01”,点击“保存”。

saveFirstLevelDialogue

saveFirstLevelDialogue

通过保存关卡,我们使得LevelHelper更新了“关卡”版块。导航至“精灵”版块,然后前往“关卡”查看关卡文件。双击关卡可以将其在LevelHelper中打开。

seeTheLevelInLH

seeTheLevelInLH

现在,让我们回到Xcode。先打开你的“RocketMouse Xcode”项目。右键点击或双击Xcode中的“资源”文件夹,选择“添加文件至RocketMouse”。

addFilesToRocketMouse

addFilesToRocketMouse

屏幕上会出现新窗口。导航至硬盘上的“资源”文件夹,选择“图片”和“关卡”两个文件夹。然后点击“添加”按钮将它们复制到Xcode的“资源”文件夹中。

AddImagesAndLevelsToXcode

AddImagesAndLevelsToXcode

Xcode中的新“资源”文件夹应当如下图所示:

xcodeIncludedImagesAndFolders

xcodeIncludedImagesAndFolders

现在,导航到Xcode中的HelloWorldScene.mm。选择并寻找加载关卡的代码。

lookForLevelLoading

lookForLevelLoading

将本部分代码中的关卡名替换为你的关卡名,也就是“level01”。新代码如下所示:

lh = [[LevelHelperLoader alloc] initWithContentOfFile:@”level01″];

现在,编译运行。

compileAndRun

compileAndRun

这样就实现了关卡的运行,很简单,不是吗?但是,当运行关卡时,你会发现如下粗糙内容:

artifacts

artifacts

导致这种情况的原因是,互不重叠的像素精灵持续性地紧接移动。如何解决这个问题呢?Cocos2d正好可以派上用场。

导航到libs/cocos2d/ccConfig.h:

fixArtifactsCocos2dConfig

fixArtifactsCocos2dConfig

在ccConfig.h中,在文件顶端寻找以下这3行代码,位置在第54行左右:

#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0
#endif

将“0”修改为“1”:

#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 1
#endif

现在,当你运行项目时,就不会看到任何瑕疵了。

创建完整关卡

让我们回到LevelHelper,添加剩余的艺术内容,这样我们才能够获得最终的完整关卡。

将小书架拖动到主屏幕上。调整位置,直到你对它与背景精灵的相对位置感到满意。

在选中关卡中的书架精灵时,点击“克隆和排列”按钮,这样才能克隆出多个同样的精灵。

cloneAndAlignTool

cloneAndAlignTool

将克隆的数值设为“7”,将补偿X设为“500”,补偿Y设为“0”。

你应当能够看到一系列蓝色或紫色的轮廓,显示精灵在关卡中的位置。当你对结果感到满意时,点击“制造克隆”按钮。

注:右键点击任何分档器按钮都会将相关区域重置为默认值。

makeClones

makeClones

现在,让我们重复这个过程,添加其余的艺术内容。

添加大书架、猫、狗和窗户精灵,根据你的偏好来设定其位置。

我喜欢将够放在窗户下方,因为狗很喜欢望向窗外。我将猫放置在老鼠洞旁边,原因显而易见。我将书架随机放置在关卡场景中。

我设计的最终关卡如下图所示:

finalLevel

finalLevel

如果你激活了LevelHelper中的“显示多边形形状”选项,你就会看到所有精灵上面都显示有物理形状。

ShowPolygonShapes

ShowPolygonShapes

在早期版本中(游戏邦注:LevelHelper 1.3),我们需要要禁用这种行为。现在,我们要启用它,因为我们在SpriteHelper场景中的更新也会导致关卡文件的更新。

如果我们在每个精灵中都选择“由SpriteHelper处理”,那么我们对SpriteHelper文件的每次改变都会直接显示在关卡中。我们不需要重新打开关卡或修改之前添加到关卡中的精灵。

HandledBySH

HandledBySH

幸运的是,“有SpriteHelper处理”是个默认设置,所以激活无需进行任何操作。让我们打开SpriteHelper文件,修改有关精灵的设置。

要实现这个目标,我们可以先打开SpriteHelper,然后再打开文件。但是,有个更加简单的方法:

我将分步解析这个过程,这样你就能够学到所有的技巧。在LevelHelper界面左侧的精灵列表中,选择精灵后在上面点击右键。现在,选择“显示SpriteHelper场景”。

selectSpriteAndShowScene

selectSpriteAndShowScene

这样,你就会看到SpriteHelper场景版面,已经为你选择了相应的场景文件。这个技巧很有用,因为有时很难想起精灵来自哪个场景。

现在,在场景上点击右键,选择“在SpriteHelper中打开”。

openInSH

openInSH

这样,所需的场景便会在SpriteHelper中打开,我们可以在这里选择想要修改的精灵,在物理标签下选择“No Physics”。

setNoPhysicsInSH

setNoPhysicsInSH

确保在修改完成后保存场景。

现在,如果你回到LevelHelper,你会看到物理形状已经消失。通过Command+Shift+S将关卡另存,命名为“level02”。

现在,如果你运行“场景测试器”(游戏邦注:按“测试关卡”按钮),你会看到只有背景精灵会移动。

让我们将其他精灵添加到视差中。要实现这个目标,首先要选择除背景精灵外已经添加到视差中的所有精灵。

selectOtherBackgroundSprites

selectOtherBackgroundSprites

现在,前往“视差”标签,选择你的视差,添加所选的精灵。

从视差的精灵列表中选择精灵,将“移动比率”设为“1”和“0”。

addOtherSpritesToParallax

addOtherSpritesToParallax

现在,如果你运行“场景测试器”,就会发现所有的精灵都会持续以相同的速度移动。

你会注意到,狗和猫精灵的形状对象都是基本的四边形。

dogQuadShape

dogQuadShape

让我们为狗和猫设置形状描绘,这样它们就能够以正确的物理行为移动。

要实现这个目标,选中狗精灵,然后使用之前介绍的方法打开SpriteHelper场景并导航到正确的场景文件中。

在SpriteHelper中,选择狗精灵,导航到“物理”版块,点击“创建形状”按钮。

selectDogForShape

selectDogForShape

现在点击和描绘狗的外形形状,而后点击“完成”。

注:

在SpriteHelper中,你可以用两个手指在触控板上的滑动来平铺视图,或者按住Option键后用鼠标拖动。

使用触控板上的手势或鼠标滚轮可以缩放场景。

createShapeOnDog

createShapeOnDog

注:点击“编辑形状”按钮可以修改形状,将其拖动到所需的点。点击形状线可以添加新的点。按住ctrl键并点击一个点,可以将这个点移除。

选中猫精灵,重复上述过程。完成后,保存场景。

现在,让我们来尝试下!回到Xcode中,右键点击“资源\关卡”文件夹,选中“添加文件至RocketMouse”,然后找到新的level02.plhs关卡。随后,将HelloWorldScene.mm中加载关卡的代码修改为:

lh = [[LevelHelperLoader alloc] initWithContentOfFile:@”level02″];

编译运行,现在你的关卡看上去显得更加有趣。

BasicLevel

BasicLevel

结语

现在,我们已经将基础关卡制作完成!但是,最为重要的是,我们学到了许多有关LevelHelper和SpriteHelper中导航以及添加和修改艺术内容的技巧。

你可以直接下载此刻的项目文件。

在第2部分的教程中,我们将学习如何添加和使用动画和传感器。我们还要创建游戏中的玩家,开始使用标签,这是执行精灵间碰撞的首个步骤。换句话说,游戏中要开始产生动作内容了!

在第3和第4部分中,游戏会变得更加有趣。除了完全执行碰撞外,我们还将制作起跳和着陆动画,学习如何杀死玩家和重新开始游戏,创建和呈现得分系统,添加其他很棒的功能。

我希望你能够坚持阅读本系列教程!掌握基础内容总是很充满挑战性的,所以如果你能够掌握本文中的所有内容,应该向你表示祝贺!

游戏邦注:本文发稿于2012年1月17日,所涉时间、事件和数据均以此为准。(本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

How to Make a Game Like Jetpack Joyride using LevelHelper and SpriteHelper [Cocos2D Edition] – Part 1

Bogdan Vladu

In this tutorial series, we will create a game similar to Jetpack Joyride using Cocos2D and Box2D. (Prefer Corona? Check out the Corona version of this tutorial!)

If you haven’t played Jetpack Joyride yet, you should check it out – it’s an incredibly polished and fun game, and best of all it’s free! :]

You could make this game with Cocos2D alone, but it would take a lot of time. To make things simpler, we’re going to use two tools written by yours truly – LevelHelper and SpriteHelper.

If you aren’t familiar with these tools, here’s a quick synopsis:

LevelHelper is a tool that makes creating levels much easier. You literally drag and drop sprites onto the scene!

SpriteHelper is a tool that creates the sprite sheets and physics shapes for your games quickly and easily.

This is going to be a complex game, and we have a lot to do, so this series will be spread over four parts. In this first part, we’ll first spend some time setting up LevelHelper. Then we’ll create a basic level with a continuous scrolling parallax, and learn how to use SpriteHelper to add and modify our art.

By the end of this series, not only will you have earned valuable experience with these tools – you will have an exciting, sophisticated game to play!

This tutorial assumes you have some basic familiarity with Cocos2D and Box2D. If you are new to either of these game frameworks, you should check out our Cocos2D and Box2D tutorials first.

Getting Started

To get started, you just need to download several things:

LevelHelper and SpriteHelper, if you don’t have them already.

Art for the game by Vicki Wenderlich, which you can download here.

The LevelHelper Xcode 4 template, which you can download here.

Note: LevelHelper supports the latest version of Box2D, but Cocos2D comes shipped with a slightly older version of Box2D. Using the LevelHelper template makes things easier for you because it pre-integrates the latest version of Box2D. If you want to use the normal Cocos2D template and integrate the latest version of Box2D yourself, check out the instructions in the official LevelHelper Cocos2D/Box2D Documentation.

Installing the LevelHelper Template

First, make sure you have the Cocos2D 1.X templates installed (i.e. not Cocos2D 2.X). If you have the Cocos2D 2.X templates installed, just download the 1.X templates from the Cocos2D download page and re-install the templates. You can always re-install the Cocos2D 2.X templates again when you need them later.

Next, unpack Cocos2dBox2dXCode4Template.zip. You will have the following folder structure:

Click once on your desktop in an empty space to make Finder the active application (and hence show its menu bar). From the menu bar, navigate to Go:

While still on the Go menu, press and hold the Option (or Alt) key, and the Library folder will now be visible. Pretty cool trick, eh? Click on it to continue.

You should now be looking at your computer’s Library folder. The full path to Library is /YOUR_HD/Users/YOUR_USER_NAME/Library.

Now navigate to Developer/XCode/Templates/Cocos2D. Copy both of the folders from the unpacked Cocos2dBox2dXcode4Template.zip file into this folder.

The resulting folder structure should look like this:

w00t you’ve installed the template! Now let’s try it out.

Creating Our Xcode Project

Open Xcode and choose File\New\New Project from the main menu.

Select the iOS\cocos2d\LevelHelper_With_Cocos2d_And_Box2d template, and click Next.

In the next dialog, name your product “RocketMouse” (no spaces), and click Next again.

Compile and run the project, and you’ll see a sample level that was made with LevelHelper:

Nice – soon you will see how easy it is to create these levels yourself! :]

Cleaning Up What We Don’t Need

We could extend the template code from here, but to give you the best understanding of how everything works we’re going to start from scratch.

So let’s clean up everything we don’t need from the template code. There are two steps: cleaning up the resources, and cleaning up the code.

Keep reading to clean this up yourself, but if you’re feeling particularly lazy, you can download the cleaned up project and just skim over these steps.

Cleaning up the resources

Inside Xcode, navigate to the Resources folder and select all files inside the Images and Levels folders.

Now Control-Click (or right click) and choose Delete.

In the pop-up window, choose Delete.

Cleaning up the code

Navigate and click on HelloWorldScene.h and delete the line b2MouseJoint* mouseJoint;

Now navigate and click on HelloWorldScene.mm. In the init method, delete the commented code and the notifications code, none of which we need.

Delete the unneeded methods used for the removed notifications.

Delete the content of all touch methods (DO NOT REMOVE THE METHODS THEMSELVES).

Delete the acceleromenter method:

Finally, delete the mouse joint release code from dealloc method:

Note: The project will compile at this point, but if try to run it it will crash with an assertion failure, as it has no level to load. Don’t worry, we will create one soon! :]

Examining the Cleaned Up Code

If you look through HelloWorldScene.m, you’ll see that there is very little code left. It creates a Box2D world, sets up Box2D debug drawing, and in the update loop runs the Box2D simulation and updates sprites to follow their associated Box2D body.

It also contains some LevelHelper setup code in init:

The first line initializes LevelHelper with an initial level. It then has a few lines to allow LevelHelper to add objects to the Box2D world and create physics boundaries and gravity based on the level settings.

Take some time to look through HelloWorldScene.mm and make sure you understand the basic idea of what’s going on so far. We’ll build up from here! :]

Preparing for LevelHelper

Let’s create two folders in the Resource folder of our Xcode project. While we don’t really need to do this, keeping our project organized will make our work easier!

In Finder, navigate to your Xcode project, open its Resources folder, and create two subfolders named “Images” and “Levels”. Important: Create these in Finder, not Xcode!

You should end up with something like this:

Creating a LevelHelper Project

Now that the project setup is complete, we can finally start creating our level with LevelHelper!

Beginning with version 1.4, LevelHelper will keep things organized in projects. This means level files are part of the project rather than individual files, as they used to be.

So let’s create a new project with LevelHelper. Open it up and go to File\New Project:

A new sheet window will appear. In the Project Name field, enter “RocketMouse,” the name of our project. Leave the Screen Size as the default, “iPhone Landscape (480×320).”

Note: When you want to create a game for all models of iPhone and iPad, you generally want to choose iPhone with Landscape or Portrait orientation. LevelHelper will automatically use SD on iPhone2G/3G/3GS and HD on iPhone4/4S and iPad1/iPad2.

If you want to create a game only for iPad, use the iPad template and inside SpriteHelper, unselect “Save SD” when creating the sprite sheets.

For iPad there is also an option to not stretch graphics. That won’t work for this tutorial, because we will be using continuous scrolling parallaxes.

Under “SpriteHelper scenes and image files directory,” choose the Images folder you just created inside the Resource folder, and click Open.

Under “Path to source code,” select the RocketMouse folder from inside the RocketMouse project folder. This is the folder that contains the LevelHelper folder. Click Open.

This setting tells LevelHelper where to go to automatically generate code, when needed.

Under “Engine” select “Cocos2d With Box2d.” Here you are selecting what code you want LevelHelper to automatically generate for you. For this tutorial, we will use Cocos2d With Box2d, but as you can see LevelHelper supports several other engines/configurations as well!

Make sure that the “Auto generate code when needed” option is selected. This tells LevelHelper to generate the code when there’s been an update to the code, or after you’ve added new tags to your project.

Under “LevelHelper scenes directory,” choose the Levels folder you just created inside the Resource folder, and click Open.

The final Project setting window should look something like this:

Note: Next to every major feature inside LevelHelper there is a “?” button. Click it to view a movie explaining that feature.

When you’re done, click the Create New Project button. A new window will appear asking you to save the project to a file.

Save the new file in the same folder as the Xcode project (RocketMouse.xcodeproj).

Now the LevelHelper window should look something like this:

But we have no image, no nothing! Time to start adding our art.

Adding Art to Our LevelHelper Project

To add our art, we need to use SpriteHelper, so go ahead and open it up.

Now navigate to where you saved the art pack for this tutorial. Select the particular files shown in the screenshot below (not all of them, just the ones shown), and drag them inside SpriteHelper.

In the Sheet Editor window on the right, uncheck the Crop option. Crop removes transparent space on sprites, but for some of our animations the sprites use transparency for placement so we don’t want the transparency modified.

For animations, it’s almost always best to uncheck Crop (to be renamed “Trim” in the next update).

Now click the Pack Sprites button at the bottom of the Sheet Editor window.

The resulting scene should look similar to this (sprites may be packed differently):

Save the scene inside the Images folder inside the Resource folder. Go to File\Save As.

In the Save dialogue window, name the scene “objects” and click Save.

If you look inside the LevelHelper window now, you’ll see that the art has automatically been added for you.

LevelHelper keeps track of all the changes inside the Levels and Images folders, just as we told it to when we created the project. Every time you add, remove or modify a file inside those folders, LevelHelper will automatically update its content.

Note: If you do not see the art in LevelHelper, click the bar above project settings and make sure the path to the Images folder is correct, and that the path does not contain any spaces.

Creating a Basic Level

Let’s start by creating a level with a scrolling floor and wallpaper background.

We first want to create a continuous scrolling parallax that will move from right to left. To do this, let’s decide how big our parallax will be. You can make it as big as you want.

Let’s make our game world the size of 8 screen sizes. Click the Game World Size button.

In the Width field, enter 3840. This is 8 multiplied by 480 (the width of the iPhone screen).

Now let’s create the background. Drag “bg” sprite into the level, and place it right at the beginning of the first screen. The first screen should be on the left side, and is demarcated by a red border.

Now we’re going to duplicate the sprite so that it covers all of our screens. With the background sprite selected, set the clone direction as in the image below so that you clone in the right direction.

Then click the green + sign. This is the clone button. (Alternatively, you could press Command+D). Continue pressing this button until the background sprite covers all sections of all eight screens. Do not go any further.

Note: You can scroll the level in LevelHelper by holding control as you drag the level, and you can zoom in and out by holding the option key as you scroll the mouse wheel.

It should look like this:

Let’s add these images to a continuous scrolling parallax. Navigate to the Parallax tab (the one that says “P”) and press the New Parallax button.

With the parallax selected, check the Continuous Scrolling option. Now select all the background sprites in the level, and click the Add Selected Scene Sprite(s) button in the parallax section.

There are still some adjustments to make to our continuous scrolling parallax. First, set the Speed preliminarily to 2.5 (we will change this later to match the movement speed of the mouse). Make sure that the Direction is set to Right to Left.

Now select all sprites in the parallax list and set the Movement Ratio to “1” and “0.” This ratio and the speed determine the rate at which the sprites will move through the parallax.

In this case, the sprites will move at the rate of 1*2.5 (ratio*speed). If we want other sprites to move at a different rate, we can modify the ratio accordingly (e.g. 0.4*2.5).

If you run Scene Tester right now (download and install it if you need to), it will move the continuous parallax, continuously!

Let’s save this level and run it in our Xcode project. Inside LevelHelper, go to File\Save Level As.

In dialogue box, enter “level01″ and click Save.

By saving the level, we caused LevelHelper to update the Levels section. Navigate to the Sprites section and then go the Levels to see the level file. By double clicking on a level, you can open that level inside LevelHelper.

Now let’s move back to Xcode. Open your RocketMouse Xcode project if it’s not already. Right click or Control-click on the Resources folder inside Xcode, and select Add Files To “RocketMouse.”

A new window will appear. Navigate to the Resources folder on your hard drive and select both the Images and the Levels folders. Then press the Add button to copy them to the Resources folder in Xcode.

Your new Resources folder inside Xcode should look like this:

Now navigate to HelloWorldScene.mm in Xcode. Select it and look for where in the code the level is loaded.

Replace the level name in this section of code with your level name, in this case “level01.” The new line of code should read:

Now compile and run.

That’s all it takes to run your level – pretty cool eh? However, when running the level you will notice some artifacts:

This is caused by pixel perfect sprites (no overlap between them) moving next to each other constantly. How to fix this? Cocos2d to the rescue.

Navigate to libs/cocos2d/ccConfig.h:

In ccConfig.h, look for these three lines of code near the top of the file, around line 54:

Change the 0 to 1:

Now when you run the project, you shouldn’t see any artifacts.

You can download the project as it stands up to this point here.

Creating the Full Level

Let’s go back to LevelHelper and add the remaining art so that we have a final level to play with.

Drag the small bookshelf onto the main screen. Drag it around until you are satisfied with its placement relative to the background sprite.

With the bookshelf sprite selected in the level, click the Clone And Align button in order to make multiple clones of this sprite.

Set the number of clones to 7, and set offset X to 500 and offset Y to 0.

You should see a series of blue or purple outlines indicating how the sprites will be set in the level. Click the Make Clones button when you are satisfied.

Note: Right clicking on any stepper button will reset the associated field to the default value.

Now let’s repeat the process to add the rest of the art.

Add in the big bookshelf, the cat, the dog and the window sprites and place them according to your preferences.

I’ve opted to put the dog under each window, because dogs like to look out the window. I’ve placed the cat next to each mouse hole, for obvious reasons. And I’ve placed the bookshelves randomly in the level.

My final level looks like this:

If you enable the Show Polygon Shapes option inside LevelHelper, you’ll see that all sprites have physic shapes on them.

Previously (in LevelHelper 1.3), we had to disable this behavior for each sprite inside LevelHelper. Now we can make it so that what we update in the SpriteHelper scene will also be updated in the level file.

If for our sprites we have “Handled by SpriteHelper” selected each time we do a change in the corresponding SpriteHelper document, the change will be immediately visible in the level. We no longer need to reopen that level or modify the previously added sprites in the level.

Fortunately “Handled By SpriteHelper” is the default setting, so we shouldn’t need to do anything to enable it. Let’s open up the SpriteHelper document and modify the settings on the sprites.

We can do this by opening SpriteHelper and then opening that document, but there’s an easier way:

I will do this process the long way so that you learn everything. In the list of sprites on the left side of the LevelHelper interface, select a sprite and Control-Click (or right click) on it. Now select Show SpriteHelper Scene.

This will take you to the SpriteHelper Scenes section and select the corresponding scene file for you. (this is very helpful, because sometimes it’s hard to remember from which scene a sprite came.)

Now Control-Click (or right click) on the scene and select “Open In SpriteHelper.”

This will open the needed scene in SpriteHelper, where we can select the sprite we want to modify and select “No Physics” under the Physics tab.

Make sure to save the scene when you’re done.

Now if you go back to LevelHelper, you’ll see that the physics shapes have disappeared. Save the level as new one by pressing Command-Shift-S. Give it the name “level02.”

If you run Scene Tester now (press “Test Level” button), you’ll see that only the background sprite will move.

Let’s add the other sprites to the parallax. To do this, first select all sprites except the background sprites that have already been added to the parallax.

Now go to the Parallax tab, select your parallax and add the selected sprites.

Select the sprites from the list of sprites in the parallax, and set the Movement Ratio to 1 and 0.

If you run Scene Tester now, all sprites should move with the same speed continuously.

Notice that the shape objects for the dog and cat sprites are basic quads.

Let’s make the shapes trace the dog and cat, so that they move with the correct physic behavior.

To do this, open the SpriteHelper scene as we did in the previous step by selecting the dog sprite and navigating to the correct scene file.

Inside SpriteHelper, select the dog sprite, navigate to the Physics section and click the Create Shape button.

Now click and trace the shape around the dog. Click Finish Shape when you are done.

Notes:

In SpriteHelper you can pan the view with 2 finger on the trackpad and move, or by holding Option key and drag with the mouse.

To zoom in or out you can use the popular pinch gesture on the trackpad or the mouse wheel.

Note: You can change a shape by clicking the “Edit Shape” button and then dragging the points as needed. You can add new points by clicking on the shape line. You can remove points by holding the Control key and clicking on a point.

Repeat the process for the cat. When you’re done, make sure to save the scene.

Now let’s try it out! Back in Xcode, control-click on your Resources\Levels folder, select Add Files to RocketMouse, and find your new level02.plhs level. Then modify the line that loads the level in HelloWorldScene.mm to level02:

Compile and run, and now your level is looking a lot more interesting!

Where to Go From Here?

So now we have our basic level! But most significantly – we’ve learned a great deal about navigating within and between LevelHelper and SpriteHelper, and adding and modifying that all-important art.

You can download the entire project up to this point here.

In Part Two, we’ll learn how to add and work with animations and sensors. We’ll also create our player, and begin working with tags – the first step in implementing collisions between sprites. In other words, the action begins!

Things will get even more interesting in the third and fourth parts. Besides fully implementing collisions, we’ll animate takeoffs and landings, learn how to kill the player and restart the game, create and display a scoring system, and add plenty of other cool features.

In other words, you definitely want to stay tuned! Getting through the basics is always challenging, so if you’ve made it this far, congratulations. In the meantime, I look forward to reading and responding to your questions, comments and suggestions in the LevelHelper forum and in the forum below. (Source: Ray Wenderlich)


上一篇:

下一篇: