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

Android游戏设计教程:游戏元素和工具

发布时间:2012-02-06 12:05:14 Tags:,,

作者:Richard A. Rogers

(本节内容选自《Learning Android Game Programming》这本书,主要分享针对Android设备开发游戏的基本原则和方法。)

创造优秀手机游戏不仅需要编写某些相当复杂的软件,还需要创造其他的成分,比如图像、动画、音效和音乐。幸运的是,这些成分都能够使用某些工具制作而成,而且许多工具可以免费使用。如果你能够上网并且拥有开发游戏的设备,那么你就可以获得所有所需的工具。

《Virgins Versus Vampires》(游戏邦注:以下简称V3)这款游戏使用Java编程语言编写而成,可在Android设备上的Dalvik虚拟机上运行。游戏使用的是名为AndEngine的开源游戏引擎和Box2D物理引擎,这两者都已经移植到Android系统上。游戏及其所有的知识产权都是使用免费的软件开发工具、图像工具和音频创造出来的,所有这些工具都将在本章节中进行说明。

需注意的是,我们正在编写的游戏是标准Android应用。它们以Dalvik/Java编写,可以完全使用Android API,它们拥有我们预想的Android应用所拥有的特征(游戏邦注:比如暂停和重新开始)。我们的游戏将会连接至AndEngine库,每个都会有供游戏使用的Android应用程序包文件(游戏邦注:下文简称“apk”)中的库副本。

软件开发工具

我们需要软件开发工具来编写软件。幸运的是,有些绝妙的工具可以用来编写手机游戏等程序。更为幸运的是,许多此类工具可以免费下载和使用,即便我们是出于商业目的而开发游戏。

Android软件开发工具包(游戏邦注:下文简称“SDK”)

如果你对Android SDK还不熟悉,先别看下面的内容,花些时间来熟悉这个工具。可以先浏览http://developer.android.com/上的下载和安装说明。

Android SDK使用Eclipse来塑造集成开发环境(游戏邦注:下文简称“IDE”)和带有Oracle的Java开发工具包(游戏邦注:下文简称“JDK”)的工具。Android网站上的安装说明会指导你如何安装Android SDK。你在本书中看到的范例和图像都是使用以下版本的组件构建而成的:Android SDK;Android SDK平台组件4.0;Android SDK工具,r14;用于Eclipse 14.0.0的ADT插件;Eclipse Helios;Oracle或Sun JDK(游戏邦注:即JDK6,也称为JDK 1.6)。

你可能使用的是比上述工具更新的版本,无需为此担心,范例代码与工具版本并无很大的关联。如果确实出现了问题,访问本书的合作网站https://github.com/portmobile/LAGP-Example-Code,看看是否有针对较新版本发布的更新内容。在这本书编写之时,当前Android版本为4.0,也就是Ice Cream Sandwich。

你还应当为自己计划支持的每种设备制作Android虚拟设备(游戏邦注:下文简称“AVD”),可以使用Android SDK和附属于SDK的AVD管理器。针对这本书中展示的范例,我们制作出很像HTC的EVO智能手机的AVD,相关数据如下:

名称:EVO

目标:Android 2.2(API等级8)

皮肤:HVGA

SD卡:128M

加速计:有

LCD密度:160

音频输出:有

摄像头:无(游戏邦注:该版本模拟器不支持,而且游戏不需要摄像头)

电池:有。

你还应当浏览下SDK教程,熟悉下整个过程,包括:创建Android项目;编写代码;构建项目;于Android模拟器上运行项目;使用Eclipse debugger、LogCat及SDK提供的其他工具来解决项目中的漏洞。如果你计划将游戏发布到Android Market上,你还需要确保它确实能够在真正的手机上良好运行,所以你还应当拥有在Android手机上加载和运行.apk文件的经验。

Android开发者站点上的指导文件很全面。如果你需要其他的指导或更多范例,还有许多优秀的Android编程书籍可供选择,包括由Lauren Darcey和Shane Conder编写的《Sam’s Teach Yourself Android Application Development in 24 Hours》。

AndEngine游戏引擎库

AndEngine是个游戏引擎库,使得针对Android设备编写二维游戏更加容易。Nicolas Gramlich费尽心思创造了AndEngine,并编写了大量项目代码。它是开源项目,所以你可以前往项目网站加入AndEngine的开发计划。

当然,我们也可以用Java来自行编写例行程序,使用Android API来执行游戏各组件。然而,利用已经编写完成的游戏引擎有诸多好处:

1、我们可以使用其他人的工作成果。当然,如果我们真想这么做的话,也可以针对Android编写自己的IDE,但是除非我们需要某些特别功能,否则这完全是毫无意义的举动。

2、以AndEngine中使用的此类开源代码为基础,我们可以根据自己的需要来扩展引擎功能。如果扩展对其他人同样有用,我们可以将这些调整内容放回开源引擎库,助其他使用者改善引擎。

3、当我们遇到问题时,我们可以向使用相同技术的开发者社区寻求帮助。有可能其他人已经解决了我们所面临的问题,可以提供问题的解决方案。

4、我们可以借用许多开发者的最优化方案。游戏需要使用相当数量的计算资源来绘制图像、计算客观物理效果、演奏音效和掌握用户输入方式。如果使用游戏引擎,我们便可以使用已经得出的最优化方案。

其他针对Android的游戏引擎目前正在开发中,本书主要阐述使用AndEngine的方法。有关AndEngine的重要网站如下:

1、AndEngine源代码库:http://code.google.com/p/andengine/

2、范例源代码库:http://code.google.com/p/andengineexamples/

3、AndEngine社区论坛:http://www.andengine.org/forums/

4、AndEngine维基页面:http://wiki.andengine.org/AndEngine

如果以上网站内容无效,只需要用浏览器搜索“AndEngine Android”,应当就可以找到当前可用的内容。

AndEngine是个.jar文件,也就是Java文档。在本章节随后的内容中,当我们开始进行游戏代码编写时,你就会知道如何配合使用这些文档和你的Android SDK项目。该引擎采用GNU Lesser GPL License,你可以出于几乎所有合理的目标来使用源代码(当然要注意这里所涉及的授权问题)。

AndEngine游戏概念

我们之前提到的电影类比法是AndEngine的理想入门方法。你的游戏就像是电影,游戏引擎包含了类似于电影制作所涉内容的诸多概念。

镜头

游戏中的“镜头”决定了游戏呈现给玩家的景象。这很像二维空间中的电影镜头。镜头可以在场景中移动,改变所呈现的景象。镜头的移动既可以由玩家来控制,也可以由程序驱动。

场景

同电影一样,游戏也是由一系列发生动作的场景构成。在电影中,场景以固定的方式编辑拼接起来。在游戏中,场景呈现顺序由游戏过程决定。游戏就像是匆忙编辑完成的电影。

层次

场景由多个图像层次组成。各层次按一定顺序叠加,很像早期用来制作卡通的动画纸。层次还可以用来创造2.5D效果,随着镜头的移动,较近的层次移动得比较远层次快。

精灵

精灵指电影中表演者的视觉呈现,无论这些表演者是人还是物品。精灵可能是动画形式,也可能不是,但它们往往在游戏过程中随场景移动。精灵质感往往从由许多精灵图片组成的大图片加载而得。

实体

在AndEngine中,实体指所有屏幕上绘制的东西。精灵是实体,显示在屏幕上的瓦片、集合形状和线条都是实体。所有的实体都拥有可以用调节器来改变的资产,比如颜色、角度、范围和位置。

调节器

调节器可以改变实体的资产,在AndEngine中它们有强大的力量。它们可以用在任何实体上,它们造成的改变既可以马上呈现也可以在规定的间隔时间内逐渐呈现。在我们的游戏中,我们频繁使用调节器来创造精灵和其他实体的效果。

纹理

2D纹理,我们通常可以利用位图图像赋予物体纹理。纹理决定实体的视觉效果,许多OpenGL图像环境是围绕纹理的使用构建而成。

纹理区域

纹理定义完整的位图图像,纹理区域定义的是区域子集。随后我们会频繁提及2D图像表现最优化,而使用纹理区域来绘制大型组合型位图中的小区域是执行这些最优化方案的关键技巧。

引擎

场景运行通过引擎来是实现。它负责让动画和调节器知道何时更新呈现的图像,协调绘图,处理用户输入事件(游戏邦注:如触点、按键和传感器事件),通常还管理游戏的进程。引擎很像是电影的制作人或导演,告诉所有人应尽的职责。

BaseGameActivity

这个类扩展了Android Activity类,将是我们所设计游戏中所有场景的基础。BaseGameActivity负责所有场景都需要做的事情,设立游戏引擎,满足Android Activity Lifecycle要求并使传感器可用。我们将在第3章中更深入地探讨这个类。

物理连接器

AndEngine的基础引擎中包含了基本物理能力,但Box2D物理引擎大幅扩展了这些能力。我们通过物理连接器将AndEngine物体同Box2D连接起来。如果你的游戏不使用Box2D物理引擎,那么你就无需有物理连接器。

Box2D物理引擎

AndEngine包含了Box2D物理引擎的开源JBox2D端口。它可以用来逼真地模拟物理物体的以下互动形式:刚体的物理效果;稳定的物体堆积;重力效果;自定义单位;碰撞和接触;滑动摩擦;正方形、圆形和多边形;多种连接类型;睡眠状态。

图像工具

任何电子游戏的开发都离不开大量的图像元素。我们需要绘制背景,还需要制作某些精灵的动画。许多工具可以用来管理电脑图像,专业化工具也相当高端精良。如果你是个图像设计师,而且知道如何使用Adobe Illustrator或其他专业工具,你可以无需阅读这个部分的内容。

相反,如果你跟我一样,缺乏足够的图像制作经验或才能,而且开发资金较少,那么可以看看这个部分的内容。本部分将主要描述我为V3这款游戏创作图像的工具(游戏邦注:下文所阐述的工具多数是免费的)。这些工具都很不错,广被专业人士所用。

你可能会试图直接从网络上获取游戏图像。如果你这么做的话,就要确保你拥有使用这些图像的权利,你可以下载图像并不等同于你有权利使用图像。如果你计划靠该游戏盈利,那么“商业化”使用其他人的图像将带来很棘手的问题。

你或许也知道,绘制图片的图像程序分为两大类别:可于用来绘制和控制图像化物体的程序(游戏邦注:也称为“绘图程序”),以及可以在画布上创建颜色位图的程序(游戏邦注:也称为“上色程序”)。每种类别都有自己的用途,两种程序在V3的创作中都会用到。

矢量图像:Inkscape

我发现用矢量图像来绘画很方便,主要有以下两个原因:

1、图画中的每个组件都被视为一个物体。在你创作最终图画时,物体可以被独自移位、缩放、旋转和编辑。

2、组件和整个图画可以在不影响分辨率的前提下轻易缩放。这种能力对精灵来说特别重要,因为其最终形态通常很小。缩放矢量图像也可能遇到问题,所以你在绘制组件时应当尽可能贴近其最终版本的大小,但在必要的时候可以灵活地缩放总是件很棒的事情。

Inkscape(游戏邦注:网址为http://www.inkscape.org/)是个非常流行的矢量绘图程序包。

许多Linux系统中会自带这个软件,它也可以在各版本Windows和Mac OS X系统中运行。其下载安装包中包含大量的“帮助”内容和教程。如果你已经精于图像制作,那么很快便可以熟练使用这个工具。如果你跟我差不多,在图像制作方面缺乏经验和才能,可能需要花长一点的时间来熟悉这个工具,但比起学习Adobe Illustrator来说依然要快得多。而且,这个工具是免费的。图2.1显示Inkscape打开一张蝙蝠图片的效果。

图2.1 inkscape(from gamecareerguide)

图2.1 inkscape(from gamecareerguide)

基础AndEngine游戏引擎难以呈现矢量图像,但是我们可以开发能够实现上述目标的扩展。在V3中,我的做法是使用Inkscape来创作图像,将它们编辑入核心内容中,缩放至合适的像素,保存成矢量版本(即.svg),以.png(即便携式网络图形)文件格式导出,如果必要的话,使用GIMP来制作透明背景。得到的位图图片(仍是.png格式)就是基础AndEngine能够识别的图片文件。

位图图像:GIMP

GIMP(游戏邦注:即GNU图像操作程序,网址为http://www.gimp.org/)是个使用者遍布全球的跨平台位图涂色程序。多数Linux系统自带该工具,该工具也是免费的。GIMP小组本身并不为Windows和Mac OS X提供支持,但现在已经出现了能够在这两个操作系统中运行的可下载版本。

图2.2 GIMP位图编辑器(from gamecareerguide)

图2.2 GIMP位图编辑器(from gamecareerguide)

图2.2显示的是与图2.1相同的蝙蝠图片。这里的蝙蝠图片以位图的形式呈现(在Inkscape中将矢量绘图保存为.png文件便可以得到)。正如你所看到的那样,结果显示图片在此等大小下更具颗粒感,带有透明的背景,这正是我们制作精灵动画手绘所需的东西。在我们呈现精灵的时候,背景将通过透明区域展示出来。

动画捕捉:AnimGet

生成动画是个乏味且颇耗时间的工作。你需要为游戏中用到的每个动画手绘、每个角度和每个姿态创作绘图。

制作3D动画是个捷径,目前可使用的3D工具很多(游戏邦注:Blender是个被设计师广泛使用的开源工具,3Ds Max、Poser和Maya也是较为流行的商业化工具)。随后,你可以根据自己需要的视角来播放2D动画。你最终会得到AVI或动画GIF文件,随后你需要将其分解成独立的帧(这样才能将它们重新整合进精灵层中)。Michael Menne创造了称为“AnimGet”的工具,可以为你完成分解工作。该工具可以在网络上的许多地方下载到(用Google搜索“AnimGet”即可),它只能在Windows系统下运行。

AnimGet背后的概念是很精巧的。该工具的原理并不复杂,只是监视你屏幕上的某个固定区域。它先复制下最初像素,然后每10毫秒查看1次。如果该区域内的像素发生改变,AnimGet会复制下该区域的新状态,以新文件的形式保存。整个过程在内存中完成,所需时间并不长,但是你需要细心地选择工具查看的区域,这样它就只会关注你感兴趣位置的动画。当你告诉AnimGet停止捕捉动画时,之前复制的图片会以独立文件的形式保存。

TileMap制作:Tiled

Tiles在电脑游戏中往往用来生成连续图像列,比如地图。在V3中,用来显示入侵的吸血鬼和障碍物。Tiled地图编辑器(可在http://www.mapeditor.org/处下载)是免费的,使用Qt跨平台库编写而成,可以在Windows、Linux和Mac OS X系统上运行。图2.3显示Tiled在tile地图编辑期间的模样。

图2.3 Tiled地图编辑器(from gamecareergudie)

图2.3 Tiled地图编辑器(from gamecareergudie)

TrueType字体制作和编辑:FontStruct

Android支持使用TrueType字体,我们在游戏中使用的就是这种字体。现在有许多工具可以用来制作和编辑TrueType字体,当然还可以使用许多其他的字体(游戏邦注:有些字体是免费的,有些字体需要购买)。很显然,FontShop制作的基于网络的FontStruct是个不错的工具,你可以在开放社区中分享你已经制作出的字体。字体可以下载,每种字体都有其相关授权。

自行制作字体需要大量的工作。我不推荐这么做,除非你实在找不到适合的字体或者你喜欢制作字体。图2.4为FontStructor网站窗口,你可以在这里制作和编辑字体。

图2.4 FontStruct字体编辑器(from gamecareergudie)

图2.4 FontStruct字体编辑器(from gamecareergudie)

音频工具

V3游戏包含两种类型的音频资产,我们需要工具来制作和编辑这两种音频。音效指持续时间较短的声音(游戏邦注:最多5秒,通常情况下少于3秒),随游戏中某些事件的发生而播放。音乐是持续时间较长的声音,通常在场景呈现时作为背景播放。

音效:Audacity

如果游戏没有音效会怎么样呢?你想要为自己的游戏制作令人惊奇的音效,Audacity(网址为http://audacity.sourceforge.net/)是个世界级的音效编辑工具,可免费在Windows、Mac OS X和Linux系统上运行。Audacity支持开发者可以输入或捕捉音效文件,编辑文件并将它们输出成各种不同的音频格式。Android偏好AAC、MP3、MIDI、Ogg Vorbis和WAV文件,这些格式的文件都可以用Audacity来处理。图2.5显示Audacity正在编辑音效。

图2.5 Audacity声音编辑器(from gamecareergudie)

图2.5 Audacity声音编辑器(from gamecareergudie)

背景音乐:MuseScore

你的游戏还需要背景音乐,格式可以是MP3、OGG或MIDI文件。当然,你可以用许多种方法来制作所需的音乐。比如,你或许有足够的才能自行用乐器弹奏出音乐,然后用设备录下。或者,你可以在网络上寻找可免费用于商业化用途的音乐文件。

我的音乐才能有限,所以我选择使用开源音乐制作工具MuseScore(网址为http://www.musescore.org/)来为V3游戏制作音乐。这个软件让你可以使用电脑键盘或配套的MIDI键盘来制作或编辑音乐。图2.6显示正在编辑音乐片段的MuseScore主界面。

图2.6 MuseScore(from gamecareerguide)

图2.6 MuseScore(from gamecareerguide)

完成音乐制作后,使用MuseScore可以将音乐保存为MIDI、MP3、OGG或WAV文件,这些格式都能为Android所识别。

实践:开场画面

我们花了这么长的篇幅来阐述游戏概念和工具,现在是时候开始编写代码,进入开发循环。我们采用的模型是,先在这里创建某Android项目的基础,然后在以下章节中不断添加新内容,直至形成完整的游戏。

我们先来看看该程序的开场画面(如图2.7所示)。屏幕在显示这个画面5秒钟后转变成空白屏幕。

图2.7 V3游戏中的启动画面(from gamecareerguide)

图2.7 V3游戏中的启动画面(from gamecareerguide)

创建游戏项目

在本书中,我们使用的是Android SDK。要使用SDK来制作V3游戏,我们先要创建一个新的Android项目。“新建”——“Android项目”对话框需要你输入下列信息:

1、项目名称:V3

2、选择“在工作区创建新项目”

3、选择默认的工作区存储位置(游戏邦注:设计师亦可根据自己的需要变更存储位置)

实践:开场画面27

4、在Build Target中选择“Android 1.6”

5、应用名称:V3

6、安装包名称:com.pearson.lagp.v3

7、Create Activity:StartActivity

8、Min SDK Version:4

通过这些步骤就可以为范例游戏创建新项目,项目包括StartActivity,不过现在它的内容只是简单的“Hello, World”。在本章节后面的版块中,我们将在开始添加代码时修改它的内容。

添加AndEngine库

如果你还未从AndEngine网站下载AndEngine库,先完成这个步骤。获得AndEngine的.jar文件的最佳地方是谷歌上的AndEngineExamples库,网址为http://code.google.com/p/andengineexamples/。

在源代码标签下,你可以在库文件夹中浏览查找.jar文件,也可以直接将整个树形源代码克隆至本地计算机。推荐使用第2种方法,这样你就已经为访问范例代码做好准备。AndEngine使用Mercurial源代码控制系统。如果你还未安装Mercurial,网站上的指导会告诉你如何实现。你将.jar文件添加到机器上之后,接下来就需要输入源代码:

1、在Eclipse Package Explorer中,扩展V3项目。右键点击V3项目,选择“新建文件夹”,在对话框中输入相关信息,这样便创建了库文件夹。

2、右键点击库文件夹,从弹出菜单中选择“输入…”

3、在下个对话框中选择“常规”——“文件系统”,使用“浏览”按钮导向你已下载的AndEngine .jar文件的存放地址。点击地址名称。

4、现在,输入对话框显示的应当是复选框无内容的地址。右侧窗口显示地址中的文件,应该有andengine.jar。点击文件名旁边的复选框,然后点击“完成”。

5、要将.jar文件包含在你的构建路径中,可以在Eclipse Project Explorer窗口中右键点击.jar文件,然后选择“构建路径”——“添加至构建路径”。这样,.jar文件也会直接显示在项目文件夹下。

添加开场画面代码

我们需要修改自动生成的StartActivity.java文件,这样才能在游戏组件加载时呈现开场画面。最终,在所有内容加载完毕之后,我们要让画面跳转到游戏菜单上。但现在,我们要实现的是保持开场画面一直可见,直到用户回到主界面。列表2.1就是StartActivity.java修改后的版本。

列表2.1 StartActivity.java

package com.pearson.lagp.v3;

import org.anddev.andengine.engine.Engine;

import org.anddev.andengine.engine.camera.Camera;

import org.anddev.andengine.engine.options.EngineOptions;

import org.anddev.andengine.engine.options.EngineOptions.

ScreenOrientation;

import org.anddev.andengine.engine.options.resolutionpolicy.

RatioResolutionPolicy;

import org.anddev.andengine.entity.scene.Scene;

import org.anddev.andengine.entity.sprite.Sprite;

import org.anddev.andengine.entity.util.FPSLogger;

import org.anddev.andengine.opengl.texture.Texture;

import org.anddev.andengine.opengl.texture.TextureOptions;

import org.anddev.andengine.opengl.texture.region.TextureRegion;

import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

import org.anddev.andengine.ui.activity.BaseGameActivity;

public class StartActivity extends BaseGameActivity {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private Texture mTexture;
private TextureRegion mSplashTextureRegion;
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH,
CAMERA_HEIGHT);
return new Engine(new EngineOptions(true,
ScreenOrientation.LANDSCAPE,
new RatioResolutionPolicy(CAMERA_WIDTH,
CAMERA_HEIGHT),
this.mCamera));
}
@Override
public void onLoadResources() {
this.mTexture = new Texture(512, 512,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mSplashTextureRegion = TextureRegionFactory
.createFromAsset(this.mTexture,
this, “gfx/Splashscreen.png”, 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene(1);
/* Center the splash on the camera. */
final int centerX =
(CAMERA_WIDTH – this.mSplashTextureRegion.getWidth()) / 2;
final int centerY =
(CAMERA_HEIGHT -
this.mSplashTextureRegion.getHeight()) / 2;
/* Create the sprite and add it to the scene. */
final Sprite splash = new Sprite(centerX,
centerY, this.mSplashTextureRegion);
scene.getLastChild().attachChild(splash);
return scene;
}
@Override
public void onLoadComplete() {
}
}

这样看上去代码似乎很多,但是在AndEngine中,开场画面只是普通的精灵。因而,我们在上述代码中实现的只是对整款游戏的初始化。下面,让我们解析代码的各个部分:

1、在输入完成后,我们的类就成为BaseGameActivity的子集。这种类可以实现所有的一般AndEngine初始化,为我们提供些许随后将会用到的方法。

2、随后,我们设定了镜头视图的尺寸。因为这是个开场画面,所以我们希望它能够占有整个屏幕。开场画面图片Splashscreen.png的像素大小为480×320,与默认Android显示尺寸相一致。

3、接下来,我们确定了镜头领域、我们将要使用的质感和质感区域。

4、现在,我们从超类BaseGameActivity处重写3个方法。每个方法对应加载过程中的一个点:

(1)onLoadEngine()方法在为这种活动加载游戏引擎时调用。我们在此处初始化镜头和引擎。关于引擎的初始化,有两点需要注意。首先,我们设定屏幕方向为横向。多数手机游戏使用的都是横向屏幕。其次,我们请求称为“RatioResolutionPolicy”的分辨率协议。在这个协议下,引擎会通过缩放功能自行调整适应不同的屏幕几何尺寸,同时保持画面纵横比不变。

(2)onLoadResources()方法在加载所需资源时调用。在上述代码中,我们创建了我们将要使用的纹理,并从开场动画图片Splashscreen.png处加载这种纹理。这个文件应当位于我们的项目工作区中名为“assets/gfx”的文件夹中,否则应用就无法运行。现在还无需担心TextureOptions设置,我们将在第5章的绘图和精灵中进行更细节化的阐述。最后,我们将纹理加载入引擎的TextureManager中。

(3)onLoadScene()方法在引擎准备呈现场景时调用。我们初始化每秒帧数记录器,创建场景,将镜头置于场景中,为开场画面制作精灵,将其依附在场景上,然后将结果反馈给引擎。AndEngine提供为开场画面提供了一种较为特别的场景(即SplashScene),但我们的这种方法也可以实现目标。

填写完StartActivity.java所需的代码后,我们需要导入图像文件。这需要以下数个步骤:

1、右键点击Project Explorer中V3项目下的资产文件夹。选择“新建”——“文件夹”,创建子文件夹gfx。

2、右键点击新建子文件夹gfx,导入文件Splashscreen.png。将这个图片放入资产文件夹中,使得我们可以使用create-FromAsset()方法来将其加载进纹理中。

在模拟器中运行游戏

在Android模拟器中运行游戏很简单,选择“运行”——“从Eclipse菜单运行”即可。如果你想要立即选择AVD,可以这么做,随后你应当可以看到开场画面呈现在模拟器窗口中。如果你需要旋转模拟器至横向,按Ctrl+F12这个键位组合即可。如果应用在强制关闭时崩溃,你可能会失去某些所需的资产。LogCat会告诉你哪些资产已丢失。

在Android设备上运行游戏

你需要访问设备制造商的开发者网站,查看Android开发工作的相关信息。只需要确保设备上运行的Android版本至少同你在创建项目时选择的版本号(游戏邦注:范例中选择的是等级4的API,相当于Android 1.6)一样新。

现在,当你选择“运行”——“从Eclipse菜单运行”时,应当可以看到在设备上运行的选项。Android SDK将会在设备上安装应用,随后开始运行该应用。我们可以使用后退或Home键返回主菜单,但是同所有的Android应用一样,你的游戏将继续在后台运行。Android智能设备不会显示游戏运行画面,虽然设备不会耗费内存周期来更新不可见的屏幕画面,但游戏的运行仍需要消耗些许内存周期。要停止或卸载应用,使用设备上的“设置”——“应用程序”——“管理应用程序”功能即可。

总结

本章涵盖了诸多内容。我们浅析了Android SDK,介绍了Android和游戏组件:镜头;场景;层次;精灵;实体;修改器;纹理;质感区域;引擎;BaseGameActivity;物理连接器。

我们介绍了许多可以用来生成手机游戏组件的工具,包括:Inkscape:用于可缩放矢量图像;GIMP:用于位图图像;AnimGet:用于动画捕捉;Tiled:用于编辑tile地图;Audacity:用于音频编辑;MuseScore:用于制作音乐。

最后,我们开始制作V3游戏。我们使用Android SDK Wizard创建Android项目,添加AndEngine库,添加代码恰当地执行AndEngine初始化,为游戏制作出开场画面。(本文为游戏邦/gamerboom.com编译,拒绝任何不保留版权的转载,如需转载请联系:游戏邦

Excerpt: Android Game Elements and Tools

Richard A. Rogers

From the overview in the last chapter, it’s obvious that creating a good mobile game involves writing some rather complex software, and also requires the creation of other components, such as graphics, animation, sound effects, and music. To be able to offer your game for others to play, you need to have commercial rights to all of this intellectual property, and the easiest way to get the rights is to create the game all yourself.

Fortunately, tools are available for all of these components, and many of them are available for free. If you’ve got an Internet connection and a development machine, you’ve got access to just about all you need.

The example game used in this book, Virgins Versus Vampires, was written using the Java programming language, which runs in the Dalvik virtual machine on Android devices. The game makes use of an open-source game engine called AndEngine and a physics engine called Box2D, both of which have been ported to Android. The game and all of its intellectual property were created using freely available software development tools, graphics tools, and audio. All of these items are described in this chapter, which also offers our first exposure to actually writing some code-specifically, a splash screen for the game.

It’s important to realize that the games we are writing are normal Android applications. They are written in Dalvik/Java, with full access to the Android application programming interfaces (APIs), and their activities have all the characteristics that we expect of Android activities (e.g., pause, resume). Our games will link to the AndEngine library, and each will include a copy of the library in the Android application package file (.apk) for the game.

Software Development Tools

We need software development tools to write software. As luck would have it, excellent tools are available for writing mobile software in general and games in particular. Even luckier for us, many of these tools are free to download and use, even if we’re creating a game we plan to sell.

Android Software Development Kit

If you are not already familiar with the Android SDK, stop right here and take the time needed to become familiar with it. The first step is to go through the download and installation instructions at the following website: http://developer.android.com/.
The Android SDK uses Eclipse for its integrated development environment (IDE) and tools that come with Oracle’s Java Development Kit (JDK). The installation instructions on the Android website will lead you through their installation (if that step is required). As of this book’s writing, the SDK is componentized. The examples and figures you see in the book were all built using the following versions of its components: Android SDK; Android SDK Platform Components through 4.0; Android SDK Tools, r14; ADT Plugins for Eclipse 14.0.0; Eclipse Helios (the version recommended for this version of the SDK); Oracle/Sun Java Development Kit (JDK 6, also called JDK 1.6).

You may be using later versions than the ones identified here, but the example code is relatively independent of version. If something doesn’t work, take a look at the book’s companion website at https://github.com/portmobile/LAGP-Example-Code and see if updates have been published for later versions. As this is being written, the current version of Android is 4.0, also known as Ice Cream Sandwich.

You should also have created Android Virtual Devices (AVDs) for each type of device you intend to support, using the Android SDK and AVD Manager that comes with the SDK. For the examples shown in the book, we created an AVD that is a lot like the HTC EVO smartphone: Name: EVO; Target: Android 2.2 (API level 8); Skin: HVGA; SD Card: 128M; SdCard: yes; Accelerometer: yes; LCD.density: 160; AudioOutput: yes; Camera: no (not supported on this version of the emulator, and not needed); Battery: yes.

You should have also at least gone through the tutorials that are provided for the SDK and be familiar with the processes of creating Android projects, editing code, building projects, running them on the Android emulator, and debugging projects using the Eclipse debugger, LogCat, and the other tools provided in the SDK. If you plan to publish your game to Android Market, you need to make sure it runs well on actual phones, so you should also have some experience loading and running .apk files on an Android phone.

The documentation on the Android developer site is excellent and very thorough. If you need a gentler introduction or more examples, many excellent Android programming books are also available, including Sam’s Teach Yourself Android Application Development in 24 Hours by Lauren Darcey and Shane Conder.

AndEngine Game Engine Library

AndEngine is a game engine library that makes it easier to write two-dimensional games for Android devices. Nicolas Gramlich led the effort to create AndEngine and wrote much of its code. The project is open source, so you are encouraged to go to the project website and join in the development effort for AndEngine yourself.

We could, of course, write our own routines in Java, using the Android APIs to implement the components of a game. Nevertheless, there are good reasons for leveraging a game engine that is already written:

- We leverage the work of others. As an extreme example, we could also write our own IDE for Android if we really wanted to, or even our own Java compiler, but unless we really need some special functionality, doing so makes no sense.

- With open-source code, like that used in AndEngine, we always have the option of extending the engine functionality any way we like. If the extension might be useful to others, we can contribute the changes back into the open-source repository and improve the engine for everyone.

- When we run into problems, we can access a community of developers using the same technology. It’s likely that someone else has already dealt with our problem and knows how to solve or work around it.

- We get the benefit of many developers’ optimizations. Games use a fair amount of computer resources to draw graphics, animate the graphics, compute object physics, render sounds, and keep up with the user input. By using a game engine, we have ready access to optimizations that have already been tuned.

Other game engines are currently under development for Android, but this book will focus on AndEngine. Important websites for AndEngine are listed here:

The source code repository for AndEngine: http://code.google.com/p/andengine/

The source code repository for examples: http://code.google.com/p/andengineexamples/

The AndEngine community forum: http://www.andengine.org/forums/

The AndEngine wiki: http://wiki.andengine.org/AndEngine

These locations may have changed by the time you read this book. If they have, just use your browser to search for “AndEngine Android,” and you should be able to find the current locations.

AndEngine comes as a .jar file-that is, a Java archive. You’ll see how to use that archive with your Android SDK project when we start our game coding later in this chapter. The engine is provided under the GNU Lesser GPL License, which allows you to use the source code and link to the binaries for just about any reasonable purpose. (Note: I am not a lawyer-you or your lawyer can read the text of the license in the file that is referenced on the repository website.)

AndEngine Game Concepts

The movie analogy we referred to earlier is a good way to approach AndEngine. Your game is like a movie, and the game engine includes concepts that are analogous to those involved in making a movie.

Camera

The “camera” of the game determines the view of the game that is presented to players. It is very much like a movie camera in two-dimensional space. The camera can pan and zoom across the scene to change the view presented. The panning and zooming can either be under the player’s control or be driven programmatically.

Scene

A game, like a movie, consists of a series of scenes where the action takes place. In a movie, the scenes are edited together in a fixed way. In games, the sequence of scenes is driven by the play of the game. Games are like movies edited on the fly.

Layer

Scenes are composed of layers of graphics. The layers are superimposed on one another, much like the animation cels used to create cartoons in the old days. Layers can also be used to introduce 2½D effects, where, as the camera pans, closer layers move faster than more distant layers.

Sprite

Sprites are the visual representation of the actors in our movie, whether those actors are people or objects. Sprites can be animated or not, but they often move about the scene during the course of game play. Sprite textures are often loaded from one large image that comprises a collection of sprite images, called a sprite sheet.

Entity

In AndEngine, entities are just about anything that’s drawn to the screen. Sprites are entities, as are tiles, geometric shapes, and lines drawn on the screen. All entities have properties, such as color, rotation, scale and position, that can be changed by modifiers.

Modifier

Modifiers change the properties of an entity, and they are very powerful in AndEngine. They can be used on any entity, and the change they cause can either be immediate or occur gradually over a specified duration. In our game, we’ll use modifiers frequently to create effects with sprites and other entities.

Texture

A texture is a 2D, generally bitmapped graphic that can be applied to objects to give them, well, texture. Textures define the way entities look, and much of the OpenGL graphics environment is built around the use of textures.

Texture Region

A texture defines a complete bitmap graphic, and a texture region defines a subset of that region. We’ll talk a lot about performance optimizations of 2D graphics later, and using texture regions to map small pieces of a large combined bitmap is one of the key tricks used to create these optimizations.

Engine

An engine runs a scene. It takes care of letting animations and modifiers know when to update the presented graphics, coordinates the actual drawing, handles user input events (touch, keys, sensors), and generally manages the progress of the game. The engine is a lot like the producer/director of our movie, telling everyone what they need to do.

BaseGameActivity

This class, which extends the Android Activity class, will be the basis of each scene in our game. BaseGameActivity does all the work common to all scenes, setting up the game engine, conforming to the Android Activity Lifecycle requirements, and enabling sensors. We’ll explore this class in more depth in Chapter 3.

Physics Connector

AndEngine includes basic physics capabilities in the base engine, but the Box2D physics engine expands greatly on those capabilities. We connect AndEngine objects with Box2D through a physics connector. If your game doesn’t use Box2D physics, you won’t have a physics connector.

Box2D Physics Engine

AndEngine includes the open-source JBox2D port of the Box2D physics engine. It can be used to realistically simulate the interaction of physical objects in the following ways (among others): Simulation of the physics of rigid bodies; Stable stacking; Gravity; User-defined units; Efficient solving for collisions/contacts; Sliding friction; Boxes, circles, and polygons; Several joint types: distance, revolute, prismatic, pulley, gear, mouse; Sleeping (removes motionless bodies from simulation until touched).

Graphics Tools

Creation of any video game requires the generation of quite a bit of graphics. Backgrounds have to be drawn, sprites rendered, and animations of some sprites created. Many tools are available to manage computer graphics, and the professional tools are incredibly sophisticated. If you are a graphic designer and know how to use Adobe Illustrator or other professional tools, you can safely skip this section.

In contrast, if you are like me, with little graphics experience (or talent) and less money to devote to game creation, this section will describe the (mostly free) tools that I used to create the graphics for V3. These tools are all very good and are widely used by professionals. A wide variety of online support for using them is available as well. If you do end up using these “free” tools, please contribute what you can to the projects that create and maintain them. If you can help with coding, testing, bug fixes, support, or documentation, that’s great. If you can’t, please consider contributing money to help keep the projects going.

You may be tempted to acquire your game graphics directly from the wide variety of graphics available on the Internet. If you do, make sure you obtain the rights to use those graphics from their owners. Just because you can download a graphic doesn’t mean you have the rights to use it. If you plan to charge money for your game, “commercial” use of someone else’s graphics is a particularly thorny issue.

As you probably know, there are two main classes of graphic programs for drawing pictures: those that allow you to draw and manipulate graphical objects as vectors (sometimes referred to as “draw programs”), and those that let you create a bitmap of colors on a canvas (sometimes called “paint programs”). Each class has its uses, and both were used in creating V3.

Vector Graphics: Inkscape

I find drawing with vector graphics convenient primarily for two reasons:

- Each component of a drawing is treated as an object. Objects can be individually repositioned, scaled, rotated, and edited as you create the final drawing.

- Components and the whole drawing can be easily scaled without losing any resolution. This capability is particularly important for sprites, which tend to be small in their final form. Scaling vector graphics is not without its pitfalls, so you should draw components as close to their final size as you can, but it’s nice to have the flexibility to scale them when necessary.

Inkscape (http://www.inkscape.org/) is a very popular vector drawing package.

It is included with many Linux distributions and also runs on all variants of Windows and Mac OS X as well. The download includes extensive Help and tutorials. If you already know what you’re doing, you’ll be up and running very quickly. If you are closer to standing in my shoes (no experience, no talent), it will take you a little longer, but it’s much quicker than trying to learn something like Adobe Illustrator. And did I mention that it’s free? Figure 2.1 shows Inkscape open with a drawing of a bat.

The basic AndEngine game engine doesn’t know how to render vector graphics, although we will explore an extension that does. In V3, my practice was to create graphics using Inkscape, edit them to my heart’s content, scale them to an appropriate pixel size, save the vector (.svg) version, export them as a .png (Portable Network Graphics) file, and, if necessary, use GIMP (discussed in the next section) to create a transparent background. The resulting bitmap image (still in .png format) is just what basic AndEngine wants for image files.

Bitmap Graphics: GIMP

GIMP (GNU Image Manipulation Program; http://www.gimp.org/) is a venerable cross-platform bitmap paint program used by many people worldwide. It ships with most Linux distributions, and it’s free. The GIMP group itself does not support Windows and Mac OS X, but download packages are readily available for both of those operating systems.

Figure 2.2 shows the same image of a bat as appears in Figure 2.1. Here the bat is rendered as a bitmap (the rendering was done by saving the vector drawing as a .png file in Inkscape). The result, as you see, is a bit grainier at this size, with a transparent background, which is just what we want for a sprite animation cel. As we display the sprite, the background will show through the transparent (checkerboard) areas.

Animation Capture: AnimGet

Generating animations can be tedious, time-consuming work. You need to create a drawing for each cel of animation, for each viewpoint, and for each pose that you will be using in the game.

A neat shortcut is to create 3D animations, using one of the many 3D tools available (Blender is a widely used open-source tool; 3Ds Max, Poser, and Maya are some of the more popular commercial tools). You can then render 2D animations in each of the views you need. You’ll end up with an AVI or animated GIF file, which you then need to break into separate frames (so you can reassemble them into a sprite sheet). Michael Menne created a utility called AnimGet that does the breakdown for you. The utility is available at several places on the Internet (just Google “AnimGet”), and it runs only under Windows.

The concept underlying AnimGet is ingenious. Rather than doing something complicated, such as parsing the animation file, this utility simply watches a defined area of your screen. It snaps a copy of the starting pixels and then comes back every 10 milliseconds to look again. If the pixels in the defined area have changed, AnimGet snaps a new copy of the area, and keeps it for a new file. The snapshots are all taken in memory, so the process can be fast, but you do need to be careful to choose the area so it contains only the animation you’re interested in. When you tell AnimGet to stop capturing views, the images are written out to individual files.

TileMap Creation: Tiled

Tiles are often used in computer games to create a regular array of graphics, such as a map or, in the case of V3, the field for the invading vampires and obstacles. The Tiled map editor (available at http://www.mapeditor.org/), which is available for free, was written using the Qt cross-platform library, so it runs on Windows, Linux, and Mac OS X. We’ll talk more about the way tiles are used in Chapter 9 on tiles, but Figure 2.3 shows what Tiled looks like in the middle of editing a tile map.

TrueType Font Creation and Editing: FontStruct

Android supports the use of TrueType fonts, which we will use in our game. Many fonts are available (either for free or for purchase), along with tools to create and edit TrueType fonts. Notably, FontShop’s web-based tool called FontStruct is offered through an open community for sharing the fonts you’ve created. Fonts are available for download, and the associated license (often Creative Commons) is shown for each font.

Creating your own font is a lot of work. I wouldn’t recommend it unless you can’t find a readymade font that will work for your game-or you like creating fonts. Figure 2.4 shows the FontStructor window of the website, where you create and edit your fonts.

Audio Tools

The V3 game will include two types of audio assets, and we need tools to create and edit both of them. Effects are short-duration sounds (5 seconds maximum, but typically less than 3 seconds) that accompany some event in the game. Music files are used to produce longer-duration sounds and are typically played in the background as a scene is being displayed and played.

Sound Effects: Audacity

What would a game be without sound effects? You’ll want to create stunning sound effects for your game, and Audacity (http://audacity.sourceforge.net/) is a world-class sound editing tool that is freely available for Windows, Mac OS X, and Linux. Audacity lets you import or capture sound files, edit them, and output them in various audio formats. Android prefers AAC, MP3, MIDI, Ogg Vorbis, or WAV files, and Audacity can deal with all of them. Figure 2.5 shows the Audacity console editing a sound effect.

Background Music: MuseScore

Your game will also need background music, in the form of either an MP3 file, an OGG file, or a MIDI file. You could create the needed music in many ways, of course. For example, you might be talented enough to play the music on an instrument and record your performance. Alternatively, you might be able to find music files online that are free for commercial use.

Having minimal musical talent, I elected to use an open-source music creation package called MuseScore (http://www.musescore.org/) for the V3 game. This software lets you create or edit music using either the computer keyboard or an attached MIDI keyboard. Figure 2.6 shows the main screen of MuseScore in the middle of editing a piece of music.

Once you’ve composed your opus, MuseScore lets you render and save the music as a MIDI, MP3, OGG, or WAV file, any of which Android knows how to play.

Getting Our Feet Wet: The Splash Screen

We’ve devoted a lot of space to game concepts and tools, but now it’s time to start writing some code, so we can get into the development groove. The model will be that we create a basic Android project here and add to it in each of the following chapters until we’ve developed the complete game.

To get going, let’s display the splash screen for the program (Figure 2.7). This screen appears for 5 seconds and then transitions to a blank screen.

Creating the Game Project

We use the Android SDK throughout this book. To begin working on the V3 game using the SDK, create a new Android Project. The New > Android Project dialog asks you for the following information:

1. Project Name: V3

2. Select “Create New Project in Workspace”

3. Use default workspace location (or any place you want)

Getting Our Feet Wet: The Splash Screen 27

4. Select “Android 1.6″ Build Target

5. Application Name: V3

6. Package Name: com.pearson.lagp.v3

7. Create Activity: StartActivity

8. Min SDK Version: 4

These steps create the project for the example game, including the StartActivity, which for now is a dummy “Hello, World” activity. We’ll fix its content when we begin to add code in a later section in this chapter.

Adding the AndEngine Library

If you haven’t already downloaded the AndEngine library from the AndEngine website, do so now. As of this writing, the best place to get the AndEngine .jar file was from the AndEngineExamples repository on Google: http://code.google.com/p/andengineexamples/

Under the source tab, you can either browse for the .jar file (in the lib folder) or clone the entire source tree to your local machine. The latter approach is recommended, as that way you’ll have ready access to the example code. AndEngine uses the Mercurial source code control system. If you don’t already have Mercurial installed, instructions on the website explain how to do so. Once you have the .jar file on your machine, you then need to import the source:

- In the Eclipse Package Explorer, expand the V3 project (if it’s not already expanded). Right-click on the V3 project, and create a lib folder by selecting New Folder and filling in the dialog.

- Right-click the lib folder and select “Import…” from the pop-up menu.

- Choose General > File System from the next dialog box, and use the Browse button to navigate to the directory where you downloaded the AndEngine .jar file. Click on the directory name (e.g., …/AndEngineExamples/lib).

- The Import dialog box should now show the directory with an empty check box. The right pane shows the files in the directory, which should include andengine.jar. Click on the check box next to the filename and then click Finish.

- To include the .jar file in your build path, right-click on the .jar file in the Eclipse Project Explorer pane, and then select Build Path > Add to Build Path. The .jar file will now also appear directly under the project folder.

Adding the Splash Screen Code

We need to modify the automatically generated StartActivity.java file so it displays the splash screen while game components are loaded. Eventually we’ll want to move on to the game menu once everything has loaded, but for now we’ll just leave the splash screen visible until the user returns to the Home screen. Listing 2.1 shows the modified version of StartActivity.java.

Listing 2.1 StartActivity.java

—–

package com.pearson.lagp.v3;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.
ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.
RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;
public class StartActivity extends BaseGameActivity {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private Texture mTexture;
private TextureRegion mSplashTextureRegion;
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH,
CAMERA_HEIGHT);
return new Engine(new EngineOptions(true,
ScreenOrientation.LANDSCAPE,
new RatioResolutionPolicy(CAMERA_WIDTH,
CAMERA_HEIGHT),
this.mCamera));
}
@Override
public void onLoadResources() {
this.mTexture = new Texture(512, 512,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mSplashTextureRegion = TextureRegionFactory
.createFromAsset(this.mTexture,
this, “gfx/Splashscreen.png”, 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mTexture);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene(1);
/* Center the splash on the camera. */
final int centerX =
(CAMERA_WIDTH – this.mSplashTextureRegion.getWidth()) / 2;
final int centerY =
(CAMERA_HEIGHT -
this.mSplashTextureRegion.getHeight()) / 2;
/* Create the sprite and add it to the scene. */
final Sprite splash = new Sprite(centerX,
centerY, this.mSplashTextureRegion);
scene.getLastChild().attachChild(splash);
return scene;
}
@Override
public void onLoadComplete() {
}
}

—–

This may seem like a lot of code to display on one screen, but in AndEngine a splash screen is like any other sprite. Thus what we’ve really done is to set up the initialization of the entire game. Let’s look at the code section by section:

- After the imports are complete, we immediately declare our class to be a subclass of BaseGameActivity. This class performs all of the common AndEngine initialization and provides us with some methods that we’ll override later.

- We then set up the dimensions of the camera viewpoint. Because this is just a splash screen, we want to display the whole scene. The splash screen image, Splashscreen.png, is 480 × 320 pixels in size, corresponding to the default Android display dimensions.

- We next define some fields for the camera, the texture we will use, and the texture region.

- We now override three methods from the superclass BaseGameActivity. Each method corresponds to a point in the loading process:

- The onLoadEngine() method is called when the game engine is loaded for this activity. We initialize the camera and the engine here. There are two things to note about the engine initialization. First, we set the screen orientation to LANDSCAPE. Most mobile games run in landscape orientation. Second, we asked for a Resolution Policy termed RatioResolutionPolicy. With this policy, the engine will adjust for different screen geometries by scaling features while maintaining the original aspect ratio.

- The onLoadResources() method is called to load required resources. Here we create the Texture we will use and load it from the splash screen image, Splashscreen.png. That file must be found in the folder named assets/gfx in our project workspace, or the application will not run. Don’t worry about the TextureOptions settings for now; we’ll talk about them more in Chapter 5 on drawing and sprites. Finally, we load the texture into the engine’s TextureManager.

- The onLoadScene() method is called when the engine is ready for the scene. We initialize the frames per second logger, create the scene, center the camera on the scene, create the sprite for the splash, attach it to the scene, and return the scene to the engine. AndEngine actually provides a special type of scene for splash screens (called SplashScene), but the way we’ve handled the matter also gets the job done.

Once we’ve filled in the code needed in StartActivity.java, we need to import the graphics file for the splash into assets/gfx. This takes just a few steps:

- Right-click on the assets folder under the V3 project in Project Explorer. Select New > Folder, and create the subfolder gfx.

- Right-click on the new gfx subfolder and import the file Splashscreen.png. Having the image under the assets folder makes it available for the create-FromAsset() method we used to load it into a Texture.

Running the Game in the Emulator

Running the game in the Android Emulator is as simple as choosing Run > Run from the Eclipse menu. If you’re prompted to choose an AVD, do so; you should then see the splash screen displayed in an emulator window. If you need to rotate the emulator to landscape orientation, pressing the key combination Ctrl + F12 will achieve that effect. If the application died with a forced close, you are probably missing one of the needed assets. LogCat will tell you exactly what was not found.

Running the Game on an Android Device

You’ll need to consult your device manufacturer’s developer site to get it properly connected for Android development work. Just make sure that the version of Android running on your device is at least as high as the one you picked when creating the project (in the example, we picked API Level 4, which is equivalent to Android 1.6).

Now when you choose Run > Run from the Eclipse menu, you should have the option of running on the device itself. The Android SDK will install the application on the device and start it running. You can use the Back or Home buttons to return to the home screen, but as with all Android applications, your game will keep running in the background. It’s not actually doing much, because the display is not visible, and Android is smart enough to not spend cycles updating an invisible screen, but the game is still burning some cycles. To actually stop or uninstall the application, use the Settings > Application > Manage Applications dialog on your device.

Summary

This chapter covered a lot of ground. We took a quick look at the Android SDK and were introduced to Android and the components of a game: Camera; Scene; Layer; Sprite; Entity; Modifier; Texture; Texture region; Engine; BaseGameActivity; Physics connector.

We looked at a collection of tools that can be used to generate the components of a mobile game, including the following: Inkscape: for scalable vector graphics; GIMP: for bitmap graphics; AnimGet: for animation capture; Tiled: for editing tile maps; Audacity: for audio editing; MuseScore: for creating music.

Finally, we started putting together the V3 game. We created an Android Project using the Android SDK Wizard, added the AndEngine library, added code to perform appropriate AndEngine initialization, and displayed a splash screen for the game. (Source: Game Career Guide)


上一篇:

下一篇: