科技: 人物 企业 技术 IT业 TMT
科普: 自然 科学 科幻 宇宙 科学家
通信: 历史 技术 手机 词典 3G馆
索引: 分类 推荐 专题 热点 排行榜
互联网: 广告 营销 政务 游戏 google
新媒体: 社交 博客 学者 人物 传播学
新思想: 网站 新书 新知 新词 思想家
图书馆: 文化 商业 管理 经济 期刊
网络文化: 社会 红人 黑客 治理 亚文化
创业百科: VC 词典 指南 案例 创业史
前沿科技: 清洁 绿色 纳米 生物 环保
知识产权: 盗版 共享 学人 法规 著作
用户名: 密码: 注册 忘记密码?
    创建新词条
科技百科——欢迎光临全球最大的互联网博物馆
  • 人气指数: 6089 次
  • 编辑次数: 1 次 历史版本
  • 更新时间: 2013-03-12
土土
土土
发短消息
相关词条
电子游戏AI
电子游戏AI
游戏设计七大常量
游戏设计七大常量
游戏设计认知
游戏设计认知
任天堂游戏设计原理
任天堂游戏设计原理
平衡游戏内部经济系统
平衡游戏内部经济系统
游戏5大设计方法
游戏5大设计方法
游戏开发者12个诀窍
游戏开发者12个诀窍
游戏视觉风格
游戏视觉风格
创造虚拟感7大原则
创造虚拟感7大原则
基于数据设计游戏
基于数据设计游戏
推荐词条
希拉里二度竞选
希拉里二度竞选
《互联网百科系列》
《互联网百科系列》
《黑客百科》
《黑客百科》
《网络舆情百科》
《网络舆情百科》
《网络治理百科》
《网络治理百科》
《硅谷百科》
《硅谷百科》
桑达尔·皮查伊
桑达尔·皮查伊
阿里双十一成交额
阿里双十一成交额
王健林电商梦
王健林电商梦
陌陌IPO
陌陌IPO
最新词条

热门标签

微博侠 数字营销2011年度总结 政务微博元年 2011微博十大事件 美国十大创业孵化器 盘点美国导师型创业孵化器 盘点导师型创业孵化器 TechStars 智能电视大战前夜 竞争型国企 公益型国企 2011央视经济年度人物 Rhianna Pratchett 莱恩娜·普莱契 Zynga与Facebook关系 Zynga盈利危机 2010年手机社交游戏行业分析报告 游戏奖励 主流手机游戏公司运营表现 主流手机游戏公司运营对比数据 创建游戏原型 正反馈现象 易用性设计增强游戏体验 易用性设计 《The Sims Social》社交亮 心理生理学与游戏 Kixeye Storm8 Storm8公司 女性玩家营销策略 休闲游戏的创新性 游戏运营的数据分析 社交游戏分析学常见术语 游戏运营数据解析 iPad风行美国校园 iPad终结传统教科书 游戏平衡性 成长类型及情感元素 鸿蒙国际 云骗钱 2011年政务微博报告 《2011年政务微博报告》 方正产业图谱 方正改制考 通信企业属公益型国企 善用玩家作弊行为 手机游戏传播 每用户平均收入 ARPU值 ARPU 游戏授权三面观 游戏设计所运用的化学原理 iOS应用人性化界面设计原则 硬核游戏 硬核社交游戏 生物测量法研究玩家 全球移动用户 用户研究三部曲 Tagged转型故事 Tagged Instagram火爆的3大原因 全球第四大社交网络Badoo Badoo 2011年最迅猛的20大创业公司 病毒式传播功能支持的游戏设计 病毒式传播功能 美国社交游戏虚拟商品收益 Flipboard改变阅读 盘点10大最难iPhone游戏 移动应用设计7大主流趋势 成功的设计文件十个要点 游戏设计文件 应用内置付费功能 内置付费功能 IAP功能 IAP IAP模式 游戏易用性测试 生理心理游戏评估 游戏化游戏 全美社交游戏规模 美国社交游戏市场 全球平板电脑出货量 Facebook虚拟商品收益 Facebook全球广告营收 Facebook广告营收 失败游戏设计的数宗罪名 休闲游戏设计要点 玩游戏可提高认知能力 玩游戏与认知能力 全球游戏广告 独立开发者提高工作效率的100个要点 Facebook亚洲用户 免费游戏的10种创收模式 人类大脑可下载 2012年最值得期待的20位硅谷企业家 做空中概股的幕后黑手 做空中概股幕后黑手 苹果2013营收 Playfish社交游戏架构

Unity 3D开发入门教程 发表评论(0) 编辑词条

目录

Unity 3D开发入门教程编辑本段回目录

Unity是目前最热门的游戏引擎之一,理由很充分——Unity具有强大的视觉编辑器,新手容易入门;功能丰富且强大;使用者多,价格便宜……

如果你想自学Unity,那就从本教程开始吧!在本教程中,你将学到如何使用Unity制作一款简单的iOS游戏——以前没经验也可以!

这款游戏的主要玩法就是:玩家要在某段时间内冲到终点,途中要避开障碍。

在制作游戏的过程中,你将逐渐了解Unity的开发环境和流程,并且学习(或复习)到游戏设计的基本概念。

本教程将分为三部分:

在第一部分,你将学习使用Unity制作简单的角色操作机制。你还会了解如何在iOS上配置项目。

在第二部分,你将学习如何使用预制的控制器对象和一些在标准软件包中建立的脚本来改进角色的移动;如何使用Unity Remote调试;如何自定义场景。

在第三部分,你将学习如何给项目中添加玩法和创建游戏设计概念,如预制件、计时器、菜单和声音等,以丰富游戏体验。

准备好学习新技能了吗?那就开始吧!

入门

沿着这个系列的教程,你会慢慢熟悉Unity开发流程,包括以下四个基本组件:

1、用Unity Editor中装配游戏场景

2、用MonoDevelop Editor编写脚本

3、用Unity Remote进行远程调试

4、通过Unity Editor发布到你的iOS设备上

在教程的第一部分,安装好Unity后,你将学习Editor界面的基本知识,然后创建一个项目,以便了解基本的游戏概念。

到第一部分的结尾,你的游戏中应该有一个可以通过触摸触发器来移动的角色。你还要在Unity Editor中和你的iOS设备中测试你的项目。

本教程使用的是第4版Unity,如果你没有的话,就先下载吧。

Unity提供30天内免费的完整试用版Unity Pro。这个版本已经足够开发出一款能在iOS上运行的游戏了。Unity在Mac和Windows系统上都可用,但本教程使用的是Mac系统。

注:Unity软件包相当大,接近1GB,下载可能需要一些时间,看你的网速了。所以如果你想马上制作本教程的游戏,那就提前下载好吧。

创建项目

下载、安装、启动Unity。如果这是你第一次启动Unity,那么软件会提示你激活版本。勾选激活免费30天试用版的Unity Pro,如下图所示:

unity_license_activation(from raywenderlich)

unity_license_activation(from raywenderlich)

然后你必须创建一个Unity帐号(如果你没有的话),确认你的邮箱地址,然后通过Unity登录帐号。

登录后,你会看到几个问题。移到列表的底部点击“Not Right Now”就可以全部跳过了。然后的最后,你就可以开始使用Unity了。

现在你看到的是Unity的界面,其中已经有一个默认项目了。如下图所示:

angrybots_sample(from raywenderlich)

angrybots_sample(from raywenderlich)

丢掉那个项目,从菜单中选择File\New Project创建新项目。你会看到如下图所示的Project Wizard(项目向导):

project_wizard(from raywenderlich)

project_wizard(from raywenderlich)

在Project Wizard上,点击Set然后选择一个存放项目的文件夹。输入“DashAndZag”作为项目的名称并点击Save,然后再点击Create Project(创建项目)(游戏邦注:你会看到对话框提示你是否保存之前打开的默认项目,没有必要的话就选择不保存。)

注:Project Wizard包含一些标准程序包,你可以在初始项目制作时导入。不过现在还用不上。到本教程的后期,你可以导入任何你需要的程序包。

Unity会关闭当前项目并重启新项目:

initial_project(from raywenderlich)

initial_project(from raywenderlich)

新画布出来了!但那些控制键、窗口和选项是怎么回事?从哪入手?

初识UI

完全习惯Unity Editor的UI确实要花上一段时间,所以多看看吧。首先要看的是右上角的Layout(布局)选项。将视图变成Wide模式:

change_layout(from raywenderlich)

change_layout(from raywenderlich)

以下是整个界面的分解图:

initial_project_annotated(from raywenderlich)

initial_project_annotated(from raywenderlich)

Project View(项目视图):你的Unity包含一个Assets文件夹,它包含的内容就显示在这个视图里。你制作的脚本、场景、预制件等Unity对象就显示在这里。

Hierarchy View(层级视图):包含当前场景中的GameObjects(游戏对象)。在Unity游戏中的所有物品都叫作一个GameObject;可以是从GameObject菜单中或导入的资源中制作出来的简单物品。你的初始项目只包含一个游戏对象:主摄像机。

Toolbar(工具条):你可以通过toolbar在场景视图或游戏视图中操作对象、改变编辑器视图的显示方式,以及预览游戏。

Scene View(场景视图):你可以在这个视图中放置游戏对象。场景视图的右上角处有一个Scene Gizmo(场景小座标),它显示了场景摄像头的当前方向。

Game View(游戏视图):这是从游戏的摄像头看游戏的视图。点击工具条的上Play按钮就进入这个视图了。另外,也可以通过点击视图上方的选项卡在场景视图和游戏视图之间切换。

Inspector(检查器): 可以通过Inspector观察游戏对象的细节,然后调整对象的属性如大小或位置等,或附加脚本调整对象的行为。

使用工具条转换工具来调整游戏对象的位置和查看场景视图,会更舒服。所以我们要先熟悉工具条的使用。

Hand工具的使用

使用Hand工具(手工具)可以控制场景的视野。

hand_tool(from raywenderlich)

hand_tool(from raywenderlich)

想下一下你自己落入一个3D场景中,里面有许多游戏对象;你能看见你面前的游戏对象,在你身后的则看不见。

你可能希望能看到更多对象(缩放),或者从左边右边观察其他对象,或者转过身看到后面的对象。这时候,你就要使用手工具了。

因为游戏对象会越来越多,为了在场景中布置对象,你会更加频繁地使用这个工具。

手工具的使用方法是,首先选中它,然后从层级视图中选择主摄像机(这样你才能在场景视图中看到东西);然后在场景中拖曳画布。

缩放视图时,可以使用鼠标滚轮或按键拖曳。按下选项同时拖曳可以旋转视图。点击右上方的场景小坐标的箭头之一,可以随时重置视图。

Handtool(from raywenderlich)

Handtool(from raywenderlich)

多练习,熟悉一下如何使用这个工具缩放/旋转场景。

因为你会经常在手工具和其他工具之间切换,所以最好能记住它的快捷键。各个工具的快捷键默认分别对应键盘上的Q(手)、W(移动)、E(旋转)和R(缩放)。

注:手工具不能移动对象,它只能改变场景的视野,看起来就好像是对象在移动。多练习用手工具操作场景视图吧。

Move工具的使用

你可以使用Move工具(移动工具)在3D空间中移动游戏对象。

move_tool(from raywenderlich)

move_tool(from raywenderlich)

选择主摄像机(游戏邦注:如果在场景视图中找不到,就在层级视图中双击它),然后点击移动工具。你应该会看到主摄像机处出现一个三个箭头的小座标。三个箭头就表示物品可以移动的方向。

move_gizmo(from raywenderlich)

move_gizmo(from raywenderlich)

红箭头表示X轴,绿箭头表示Y轴,蓝箭头表示Z轴。选中对象后左击,然后朝小坐标内部(白线框)拖曳,就可以转换或移动游戏对象了。

选择主摄像机,然后移动。看看检查器的转换组件。X、Y、Z值就表示游戏对象的位置。移动对象时,你可以看到这些值在变化。

TransformComponent(from raywenderlich)

TransformComponent(from raywenderlich)

使用移动工具或输入XYZ值都可以改变游戏对象的位置。

想把游戏对象朝某个方向移动时,只要选择小座标上的对应箭头,左击并拖曳就可以了。将游戏对象往X轴方向的移动,你会发现在检查器中,只有X值发生变化。请在Y轴和Z轴方向做相同的测试。

inspector_after_x_move(from raywenderlich)

inspector_after_x_move(from raywenderlich)

现在,你已经知道如何移动场景视图,以及如何移动对象。干得不错!

Rotate工具的使用

你可以使用Rotate工具(旋转工具)在3D空间中旋转游戏对象。

rotate_tool(from raywenderlich)

rotate_tool(from raywenderlich)

为了学习旋转工具的用法,我们应该更加详细地了解场景小座标。场景小座标就在场景视图的右上角,它有不同的模式。

其中一个模式(见下图的右半边)是自由视图,你可以从3D透视图中察看场景。如果你想知道游戏在3D空间中的样子,这个模式是非常管用的。

点击小座标下方的字就切换到等角视图(见下图的左半边)。旋转游戏对象时比较适合使用这个模式。

scene_gizmo_perspective_isometric(from raywenderlich)

scene_gizmo_perspective_isometric(from raywenderlich)

另一个模式是X轴视图,也就是从X轴观察场景。如果你想沿着Y轴或Z轴移动游戏对象,同时保持X轴不变,就可以使用这个模式。

scene_gizmo_x(from raywenderlich)

scene_gizmo_x(from raywenderlich)

类似的,还有Y轴视图和Z轴视图。原理同X轴视图。

scene_gizmo_y(from raywenderlich)

scene_gizmo_y(from raywenderlich)

scene_gizmo_z(from raywenderlich)

scene_gizmo_z(from raywenderlich)

选择主摄像机,右击小座标选择“Free”就切换到自由透视模式了。

change_to_free(from raywenderlich)

change_to_free(from raywenderlich)

点击小座标下的字可以在等角模式和透视模式之间切换。依次点击X、Y、Z轴模式,看看场景小座标和场景视图的变化。

再次选择自由视图,然后测试旋转效果。在主摄像机仍然选中的情况下,点击旋转工具。你应该会看到如下图所示的三个不同颜色的圈,分别代表三个旋转轴向。

rotate_gizmo(from raywenderlich)

rotate_gizmo(from raywenderlich)

左击主摄像机的中心,然后用鼠标拖曳。注意,当你旋转对象时,你会发现检查器的Transform\Rotation属性在变化。你也可以手动修改这些属性值。

在旋转时点击主摄像机的中心,就是在所有轴向上做自由旋转。你还可以绕着一个轴旋转游戏对象,比如,点击红色圆圈选中它,然后拖曳对象,就是在X轴上旋转对象了。对绿色和蓝色圆圈做同样的测试。

视野

现在,你有必要学习一下局部视野和全局视野之间的差别。

Global vs Local(from raywenderlich)

Global vs Local(from raywenderlich)

通过Inspector\Transform\Rotation将主摄像机的旋转属性值重置为0,0,0,点击工具条上的“Local”按钮。然后选择移动工具,这样你就可以看到场景小座标了:

global_local_aligned(from raywenderlich)

global_local_aligned(from raywenderlich)

注意,场景小座标和主摄像机的小座标是类似的,两个小座标的三个轴都分别代表相同的方向。现在,在检查器中设置Transform\Rotation的值为0,0,-20,就是沿着Z轴旋转主摄像机。

global_local_after_z_rotation(from raywenderlich)

global_local_after_z_rotation(from raywenderlich)

注意,主摄像机的小座标现在是沿着Z轴旋转的——这就表示这个对象的这个轴处于它的本地坐标。这与场景小坐标是不同的,因为场景小坐标代表的是整个空间的方向。切换到全局视图,看看有何不同。

在教程的后半部分,你将学习移动游戏对象和发现它与不同空间(局部或全局)的关系。

看一下旋转后的主摄像机,如果你现在想在局部空间视图中把它朝X轴方向移动,最终结果会不同于在全局空间中把它朝X轴移动。记住这一点,以后会用到!

再学习下面的内容以前,请再次将旋转值重置为0,0,0。

Scale工具的使用

你可以使用Scale工具(缩放工具)调整游戏对象的大小。

ScaleTool(from raywenderlich)

ScaleTool(from raywenderlich)

与其他游戏对象操作工具一样,你只能在三个轴向收改变对象的大小。你也可以选择在Inspector\Transform面板中修改属性值来调整对象的大小。

选择主摄像机,注意,缩放小座标是由位于各轴末端的方形控点和中心的方形控点组成的。

沿着所有轴自由缩放的方法就,选择对象中心的方块后保持左击,然后朝外移让对象变大,朝内移让对象变小。看一看Inspector\Transform\Scale属性,你会发现当你缩放对象时,属性值会发生变化。

ScaleComponent(from raywenderlich)

ScaleComponent(from raywenderlich)

选择代表X轴的红色控点,按下同时朝外移动,这样对象就变大了。你会发现在检查器的Inspector\Transform面板上,只有X值改变了。在Y轴和Z轴上做同样的测试。

在Inspector\Transform面板中重置主摄像机的设置,输入如下值:

Position(位置): 0,1,-10

Rotation(旋转): 0,0,0

Scale(缩放): 1,1,1

结果如下图所示:

transform_reset(from raywenderlich)

transform_reset(from raywenderlich)

本教程之后还将介绍其他编辑器界面的组件,包括使用Play按钮预览游戏,和使用Unity调试器。

添加游戏对象

你已经学习了基本概念,现在可以开始添加游戏对象了——摄像机已经寂寞好久了。

目前摄像机面对的世界还是空荡荡的。添加一个表示角色的方块,再添加一个表示地面的平面(角色将在上面移动)。

当你使用Unity设计游戏时,最好先思考游戏玩法,而不要考虑角色是怎么样的。这样你才能集中精神优化玩法和角色的移动方式,而不是分心思考角色的外观。

另外值得注意的是,虽然Unity是一个非常好的游戏引擎,但你不应该用它制作图形资源。有许多工具非常适合制作图形部件,而Unity更擅长导入各种工具制作的资源。

游戏开发的分工通常是这样的:游戏开发人员使用Unity开发玩法,同时,图像设计师使用他们最拿手的图像工具制作图像。当图形资源能够达到美化游戏的目的时,二者就可以融为一体了。

选择Game Object\Create Other\Plane,添加一个表示地面的平面。

这个新平面游戏对象会出现在层级视图中。在层级视图中选择平面,然后设置Transform\Position值为0,0,0。在检查器中将它的大小设置为50、1、50。你的场景应该接近下图:

plane_after_transform_changed(from raywenderlich)

plane_after_transform_changed(from raywenderlich)

接下来是添加一个角色游戏对象,用方块表示。对啦,就是方块英雄!

选择Game Object\Create Other\Cube,这样层级视图中就出现一个方块游戏对象了。在层级视图中选中方块,然后在检查器中设置Transform\Position值为0,0,0。结果如下图所示:

cube_after_transform_changed(from raywenderlich)

cube_after_transform_changed(from raywenderlich)

点击移动工具,然后在场景小座标上点击Y轴,将对象的移动限制在Y轴上。移动方块,使它位于平面(地面)之上。你还可以通过设置位置属性值为0,1,0达到相同的效果。

现在我们迎来激动人心的时刻了——点击工具条上的Play按钮,预览你的游戏:

play_tool(from raywenderlich)

play_tool(from raywenderlich)

你现在就是在用Unity Editor测试你的游戏。你应该换到游戏视图,结果如下图所示:

play_result_darkness(from raywenderlich)

play_result_darkness(from raywenderlich)

你现在看到的是通过场景的主摄像机看到的游戏。你的角色,这个方块英雄就站在地面的远处——多么孤独而勇敢的存在啊!

这个游戏还没有什么看点,因为你还没添加任何组件来调整角色的行为。并且,场景有点暗了。我们先来解决场景问题,也就是给场景添加一个光源。

再次点击Play按钮,退出游戏预览。回到场景视图,添加光源:选择Game Object\Create Other\Point Light。像平常一样,移动光源到合适的地方,然后进一步调整位置。在检查器中设置transform position属性值为0,0,0。

现在调整光源的高度和亮度,以便看清场景。给你提示一下:使用移动工具,只沿着Y轴移动。

高度调好后,就可以调亮度了:在Light组件中修改Range(范围)和Intensity(强度)设置。如果想看得更清楚一点,可以利用手工具来环转场景。

有了足够的光之后,点一下Game选项卡(不是点击Play按钮)切换到游戏视图,你就可以看清场景了。来回移动光源,直到你可以看到角色。

game_light_added(from raywenderlich)

game_light_added(from raywenderlich)

调整完后,点击Play按钮检查修改效果。当你切换到游戏视图时,你看到的结果应该如下图:

game_light_added(from raywenderlich)

game_light_added(from raywenderlich)

恭喜你啦,你已经添加完教程现阶段要求的所有游戏对象了。记住,你应该先设计游戏玩法,然后再考虑图像。

既然你已经做好一些有意义的东西了,那就将结果作为场景保存到项目中吧。项目可以由一个或多个场景组成。你可以把一个场景等同于游戏的一个关卡。

在这个教程中,你可以将各个部分当作一个场景。这是一个仿造的游戏关卡的概念,但你可以重复利用一个场景的资源。

保存场景的方法是选择File\Save Scene,然后在Save Scene的对话框中输入场景名称为Level_1。你的项目视图将更新成你刚做好的场景。

DashAndZag-PC-Mac-Linux-Standalone(from raywenderlich)

DashAndZag-PC-Mac-Linux-Standalone(from raywenderlich)

事件函数

游戏现在还是静态的。我们必须让它“活”起来。

你可以通过制作自己的脚本或使用已打包的脚本,附加到相应的游戏对象上,从而让对像活动起来。例如,在本教程的第一部分,你做了一个“通过触摸移动角色”的脚本。你制作的这个脚本应该响应触摸事件,以改变方块英雄的位置和旋转情况。

Unity支持的脚本语言有:JavaScript、C#和Boo。本教程使用的是JavaScript。Unity的脚本语言包括预定义的事件函数,你可以用它定义游戏对象的行为。

最常用的事件函数是Update()。如果你在脚本中定义这个函数,每一帧它就会被调用一次。每一帧游戏显示就会绘制一次,所以Update函数就负责帧中的显示。

游戏以每秒某数量的帧运行,记住,这个速率根据游戏运行的平台、其他应用占用的系统资源会有所不同。这意味着,你不应该把东西做得太密集,并且你不可能估计到那个速率到底是多少。

另一个预定义事件函数FixedUpdate()不同于Update(),它是个固定的帧速。如果你的脚本定义了这个方式,它就会每隔一段固定的时间调用一次(相比之下,Update方式的每一次调用可能各不相同)。

因为物理是非常讲究时间的,所以更适合使用FixedUpdate()函数处理任何物理相关的活动。例如,现在有一个使用物理的游戏对象,如刚体(之后会学习到)。当这个对象与另一个对象相撞时,你必须计算作用到对象上的力量,这就要通过FixedUpdate()函数来实现。

至于像改变对象的位置或旋转之类的操作,最好使用Update()函数。

第三个实用的函数是Start(),在第一帧update发生以前调用。一般会把初始化放在这里。

最后是Awake(),它在游戏开始时调用。也是放初始化代码的好地方。

触摸

我们来尝试一下。创建一个新脚本:选择Assets\Create\Javascript。这样,一个带默认名称“NewBehaviorScript”的新脚本就出现在你的项目视图中。点击脚本名称,重命名为“MoveSimple”。

双击脚本打开它。它应该出现在附带的MonoDevelop编辑器里,包含以下代码:

#pragma strict

function Start () {

}

function Update () {

}

Start()和Update()函数已经帮你写好了,因为它们是常用的事件函数。如果你不需要Start()函数,那就去掉它。添加如下变量,它们是用来控制方块英雄的移动和旋转速度:

var speed : float = 3.0;
var rotateSpeed : float = 10.0;

用如下代码替换空白的Update():

function Update () {
// Detect mouse left clicks
if (Input.GetMouseButtonDown(0)) {
// Check if the GameObject is clicked by casting a
// Ray from the main camera to the touched position.
var ray : Ray = Camera.main.ScreenPointToRay
(Input.mousePosition);
var hit : RaycastHit;
// Cast a ray of distance 100, and check if this
// collider is hit.
if (collider.Raycast (ray, hit, 100.0)) {
// Log a debug message
Debug.Log(“Moving the target”);
// Move the target forward
transform.Translate(Vector3.forward * speed);
// Rotate the target along the y-axis
transform.Rotate(Vector3.up * rotateSpeed);
} else {
// Clear the debug message
Debug.Log(“”);
}
}
}

保存修改。

这份代码首先寻找鼠标点击事件,特别是鼠标左键的点击。当使用GetMouseButtonDown函数时,参数“0”表示左键单击,“1”表示右键单击,“2”表示中键单击。如果检测到单击事件,代码就会使主摄像机生成一道光束(想一下激光笔),移到鼠标点击的位置。

collider.Raycast()函数会检测脚本中的碰撞器是否被光束击中。如果碰撞器被击中,collider.Raycast()就会返回“true”。这个函数调用有3个参数:

1、你构建的光束

2、RaycastHit对象,如果碰撞器被击中,还包含更多细节

3、光束的长度参数

假设结果是“true”,接下来的代码就会让角色向前移动,speed变量决定它的速度,rotateSpeed变量决定它的旋转。transform.Translate()函数将游戏对象按它的Vector3输入指定的方向和距离进行移动。

Vector3是代表一个具有方向和长度或大小的对象的3D矢量。这个矢量可以分解成X、Y和Z组件。

在代码中,你的方块英雄向前移动,距离增加器是根据speed变量计算的。Vector3.forward与Vector3(0,0,1)一样,速度增加器为3就是把方块按Vector3(0,0,3)移动。

角色的移动方向与角色的本地座标有关。选择方块,然后使用移动工具,你看到的Z轴方向就是角色将前进的方向。

transform.Rotate()函数会根据由Vector3输入指定的角度旋转游戏对象。Euler角就是用来描述游戏对象的方向的。Euler角Z度就是绕着Z轴旋转,Euler角X度就是绕着X轴旋转,Euler角Y度就是绕着Y轴旋转。

在以上代码中,角色使用Vector3.up或Vector(0,1,0)作旋转动作,表示绕着Y轴移动。旋转角度按rotateSpeed增加。旋转与角色的本地座标有关。所以你的方块英雄将绕着它的Y轴旋转,你知道的,这与全局的Y轴是不一样的。

注:真正的游戏绝对不会使用这类移动方式来控制角色。本教程是为了介绍关于移动游戏对象的基本概念才使用的。教程后面使用的将是更真实的移动方式。

这份代码包含两个Debug.Log()语句。当游戏在运行时,log输出就会在Unity控制器中打印。在Unity Editor的底部,你可以看到最后一次的log输出。你还可以通过选择Window\Console看到前一次log输出,或清除log记录。

你应该时时注意Unity Editor底部的log输出,因为那就是显示脚本错误的地方。

通过代码定义行为后,就可以把行为赋给游戏对象了。在层级视图中选择方块,然后选择Component\Scripts\Move Simple。这个步骤就是添加一个脚本行为给游戏对象,你也可以简单地选择你已经做好的脚本(名称为MoveSimple)。

after_movesimple_added(from raywenderlich)

after_movesimple_added(from raywenderlich)

注意,检查器现在包含一个MoveSimple的脚本段落。你可以在检查器视图中看到你在脚本、speed和rotateSpeed中定义的公共变量。你现在可以只调整这些公共变量,而不必变更基础脚本。

这意味着如果在场景中有两个角色带有MoveSimple脚本,那么只要增大Inspector\Move Simple\Speed的数值,就可以让其中一个角色移动得比另一个更快。

点击Play预览游戏。点一下角色让它移动,注意检查器中的位置和旋转属性的变化。

gameview_transform_moved(from raywenderlich)

gameview_transform_moved(from raywenderlich)

注意,位置从0,1,0变成0,1,3了——换句话说,根据速度增加器,角色在Z轴上移动了3。旋转也从1,1,1变成1,10,1,这是旋转速度增加器造成的结果。

游戏在运行时,你可以在检查器中调整速度和旋转速度的变量。点击角色后,增加速度值,观察角色位置的变化。

停止游戏,注意速度和旋转速度变量会恢复到初始值。在游戏运行中你做的任何调整都是暂时的。这有助于你尝试不同的数值,结束预览后回到初始设置。如果你决定改变设置,那就要在测试游戏以前进行。

注意,当你运行游戏时,控制器记录正确的排错声明,这取决于角色是否被点击。

摄像机的设置

你应该已经注意到,当你移动方块英雄时,它就会离摄像机越来越远——感觉不太好。就像无微不至的父母照看刚学会走路的孩子,你希望让主摄像机在角色后面一直跟着。这是第三人称射击游戏的典型做法。

选择Assets\Import Package\Scripts,在Items to Import窗口中选择SmoothFollow脚本,然后点击Import:

import_smoothfollow(from raywenderlich)

import_smoothfollow(from raywenderlich)

注:如果当你选择Assets\Import Package\Scripts时没有看到导入选择的对话框,那么就试一下退出Unity后重新启动。这么做对我来说是有效的。

在你的项目视图中应该可以看到新的Standard Assets文件夹。浏览它的下级文件夹可以看到SmoothFollow脚本。双击这个脚本,在MonoDevelop中打开,这样你就看到了代码的关键部分。

var target : Transform;

以上表示被追踪目标的公共变量。使用目标的转变信息来设置追踪者(主摄像机)的位置和旋转。

追踪者的位置和旋转在LateUpdate()中设置,这是另一个预定义事件函数。这个函数是在Update()函数完成后调用的,一般你会把与发生在Update()中的操作有关的代码放在LateUpdate()中。

当方块英雄的位置和旋转在MoveSimple脚本定义的Update()中改变了,摄像机就会在SmoothFollow脚本的LateUpdate()函数中更新它自己的位置和旋转。

..
var wantedRotationAngle = target.eulerAngles.y; // 1
var currentRotationAngle = transform.eulerAngles.y;
..
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
..
var currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);

..
transform.position = target.position; // 2
transform.position -= currentRotation * Vector3.forward * distance;
transform.position.y = currentHeight;
..
transform.LookAt (target); // 3

以上代码段落有几个关键点:

1、找到追踪者必须旋转的角度,以匹配目标的旋转。旋转是绕着Y轴进行的。

2、追踪者在目标之后沿着Y轴移动,距离由距离变量决定。追踪者还根据目标的旋转绕着Y轴旋转。最后,确保追踪者在目标上方的高度固定。

3、确保追踪者总是面向目标。

现在将脚本赋给主摄像机。在层级视图中选择主摄像机,然后选择Component\Camera Control\Smooth Follow:

after_smoothfollow_added(from raywenderlich)

after_smoothfollow_added(from raywenderlich)

检查Smooth Follow的新段落是不是添加到主摄像机的检查器中。

注意,Target变量现在还没赋值。你要把方块这个游戏对象指定给这个输入。在主摄像机仍然选中,Smooth Follow脚本在检查器中可见时,将方块游戏对象从层级视图中拖曳到Target变量。或者,你也可以点击Target值旁边的带小点的圆圈,从对象列表中选择。

smoothfollow_target_added(from raywenderlich)

smoothfollow_target_added(from raywenderlich)

现在,Target变量已经与方块(角色)连系起来了。

点击Play按钮。你应该可以马上看到视野的变化,你现在是从给定的高度观察角色。点击角色移动它,观察摄像机如何追踪角色。注意主摄像机在检查器中的转变信息会随着方块英雄的移动而发生变化。

停止游戏,保存后再进行下一步。

在iOS上部署

你一定等不及想看看游戏在iOS设备上的运行情况。好消息是,Unity Pro试用版允许你在iOS上测试你的项目!

最好能在真正的设备上测试你的Unity项目。你总不希望仅在模拟器上测试吧,即使你可以做到。因为游戏开发严重依赖基础硬件,所以只有在真正的设备上测试,才能更容易发现性能问题。

在iOS设备上测试以前,你必须是已注册的苹果应用开发者,具有设备部署能力。如果你不是,那么就花99美元注册一下吧。

Unity可以把你的游戏建成X代码项目,使你可以在iOS设备上部署。选择File\Build Settings:

build_settings(from raywenderlich)

build_settings(from raywenderlich)

选择iOS平台,然后点击Switch Platform。再点击Build Settings对话框底部的Player Settings按钮。Unity Editor的检查器会显示Player Settings,你可以自定义你的iOS部署。请做以下调整:

默认方向:横版向左

player_settings_resolution(from raywenderlich)

player_settings_resolution(from raywenderlich)

其他设置

捆绑标识符:这样你的应用才能顺序部署到设备上。

SDK 版本: Device SDK

瞄准的iOS版本:4.3

player_settings_other(from raywenderlich)

player_settings_other(from raywenderlich)

返回到Build Settings对话框。在Scenes In Build窗口添加场景。因为你的项目只有一个场景,所以很容易添加。点击Add Current按钮就可以添加Level_1 scene了。

build_settings_scene_added(from raywenderlich)

build_settings_scene_added(from raywenderlich)

点击Build按钮,启动创建进程。你可以指定某个地方保存X代码项目:在Save As中输入DashAndZag,然后选择Save。

Unity现在就建立了一个项目,打开包含X代码版本的文件夹。这个项目的名称是Unity-iPhone.xcodeproj。

打开X代码的项目,确保scheme设置成Unity-iPhone,选择你的设备,然后建立项目。

xcode_scheme(from raywenderlich)

xcode_scheme(from raywenderlich)

运行应用。你首先会看到带Unity默认标志的画面。然后,你的游戏就出来了:

game_ios(from raywenderlich)

game_ios(from raywenderlich)

触碰方块英雄,观察它的移动。你已经将你的第一个Unity项目部署到iOS上了!

操作

等等,事情还没完呢!

如果你玩得更久一点,你会注意到一件奇怪的事。你可以通过一根手指触摸方块来移动它。但是,当你用两根手指放在离它等距离的地方时,方块也会移动。这是怎么回事?

从MoveSimple脚本中调出这行代码:

var ray : Ray = Camera.main.ScreenPointToRay
(Input.mousePosition);

这行代码就是让摄像机发出的光束移到触摸点。Input.mousePosition就表示触摸点。当项目在iOS设备上运行时,Input.mousePosition是按当前所有触摸的平均位置计算的,所以当你的手指那么放时,角色就移动了。

你应该修复这个问题,以免困扰用户。你可以使用Unity中的触摸相关函数来检测触摸事件,以便找到更准确的触摸位置。

开打MoveSimple脚本。在顶部(其他变量所在的地方)添加一个标记,表示你可以使用触摸输入:

private var isTouchDevice : boolean = false;

你可以在iOS和Unity Editor中测试。如果你只在iOS上测试,那么你就可以忽略触摸检查逻辑,只使用触摸相关的函数。

下一步是添加一个Awake()函数,它会执行运行期检查,以检测游戏是否在iOS环境下运行。Awake()函数只调用一次,也就是在游戏载入的时候:

function Awake() {
if (Application.platform == RuntimePlatform.IPhonePlayer)
isTouchDevice = true;
else
isTouchDevice = false;
}

Application.platform返回游戏正在运行的平台。RuntimePlatform.IPhonePlayer表示游戏正在iOS上运行。

最后,将你的Update()函数作如下修改:

function Update () {

var clickDetected : boolean;
var touchPosition : Vector3;

// Detect click and calculate touch position
if (isTouchDevice) {
clickDetected = (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began);
touchPosition = Input.GetTouch(0).position;
} else {
clickDetected = (Input.GetMouseButtonDown(0));
touchPosition = Input.mousePosition;
}

// Detect clicks
if (clickDetected) {
// Check if the GameObject is clicked by casting a
// Ray from the main camera to the touched position.
var ray : Ray = Camera.main.ScreenPointToRay
(touchPosition);
var hit : RaycastHit;

保存修改。

你正在使用两个新本地变量,clickDetected和touchPosition,检测点击和保存点击位置。如果是在iOS上运行,那么就是通过查看触摸来检测点击。然后,根据第一次触摸的位置来计算点击位置。如果你不是在iOS上运行,那么逻辑如之前的一样。

在重建项目以前,请关闭X代码项目。现在,从Build Settings对话框中重建。如果出现以关于Build文件夹已存在的警告,那就选择Replace。

build_replace_warning(from raywenderlich)

build_replace_warning(from raywenderlich)

X代码项目重建好后,在iOS设备上运行游戏。检验是否能移动方块英雄,以及用两根手指移动它的问题是否解决。

结尾

恭喜啦,你已经初步掌握Unity的基本概念和在iOS上部署!

在本教程的下一部分中,你将学习如何改进方块英雄的移动和完善场景。另外还要做一点调试工作!

而今天我们将添加一些函数去丰富这一项目,即包括更有趣的玩家移动和更棒的游戏场景。

让我们开始吧:场景的改变

首先打开我们在第一部分教程中所创建的Unity项目。

今天的教程将基于一个全新的场景,从而让玩家可以在之后轻松地使用之前的场景作为参考。

选择File\Save Scene as…并将新场景命名为Level_2。新的Level_2场景将出现在项目视图中。

之前场景中的所有资产(游戏邦注:包括脚本)都能够用于新场景中。在你可以改变GameObjects在Level_2场景中的呈现而不会影响到Level_1场景中相同的对象。

玩家的移动

首先我们需要强化玩家的移动。现在我们的Heroic Cube始终都是向前移动,并向右旋转。这种移动并不顺畅,也不有趣。

角色控制器是Unity的组件,我们能够将其附加到GameObject去创造更加真实的移动。我们可以基于脚本函数去操纵角色控制器。

举个例子来说吧,我们可以调用预先定义的SimpleMove函数去移动角色。在Vector3中SimpleMove函数代表执行移动的速度。角色的移动会自动算上重力,从而让它能够爬上斜坡也能爬下楼梯。

同时角色还能滑过各种障碍无需你去编写代码提示他们。

为了更好地理解这一点,我们可以在Hierarchy View中选择Cube GameObject,并选择Component\Physics\Character Controller。你将看到一个对话框在询问是否用CharacterController替换Box Collider。

replace(from raywenderlich)

replace(from raywenderlich)

点击替换。

在Inspector中你可以看到一个有关角色控制器的新组建。你需要创造一个全新的脚本去控制玩家的移动,从而让你无需再将MoveSimple脚本附加到Heroic Cube上。

move simple(from raywenderlich)

move simple(from raywenderlich)

在Inspector点击MoveSimple脚本组件右边的齿轮图标,并选择移动组件。脚本将不再出现于Inspector。

reset(from raywenderlich)

reset(from raywenderlich)

通过选择Assets\Create\JavaScript创建一个新的JavaScript资产,并将其命名为MoveAround。在MonoDevelop Editor双击打开新脚本。选择存根函数并添加如下代码:

var speed : float = 3.0;
var rotateSpeed : float = 3.0;

function Update () {
var controller : CharacterController = GetComponent(CharacterController);

// Rotate around y – axis
transform.Rotate(0, Input.GetAxis (“Horizontal”) * rotateSpeed, 0);

// Move forward / backward
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = speed * Input.GetAxis (“Vertical”);
controller.SimpleMove(forward * curSpeed);
}

@script RequireComponent(CharacterController)

保存你所做出的改变。

脚本的最后一行内容明确了这一脚本只能附加到GameObject(游戏邦注:拥有一个角色控制器组件)。

Update()函数拥有角色控制器组件的句柄。然后它将围绕着y轴(基于代表着左/右移动的输入内容)进行旋转。左/右移动是默认地由左/右箭头和A/D键所控制。

Input.GetAxis()值的范围是从-1到+1。负值代表逆时针方向,而正值则代表顺时针方向。

基于来自Input.GetAxis(“Vertical”)的输入内容,SimpleMove函数能够向前或向后移动角色。这一输入内容是由向上/向下箭头或W/S键所触发的。就像水平输入一样,Input.GetAxis()值的范围是从-1到+1,负值和正值将分别触发向后和向前的移动。我们将使用倍速器去控制和旋转角度或移动距离。

将新脚本附加到Heroic Cube。

当你完成了这些设置后,你便能在玩家的Inspector上看到新的Move Around脚本组件。

character controller(from raywenderlich)

character controller(from raywenderlich)

为什么不使用Unity Editor去旋转Heroic Cube?点击游戏按键并感受左右旋转,向前并向后移动的乐趣吧!

使用左/右/上/下箭头进行移动,同时测试W/A/S/D按键。多亏了角色控制器组件和脚本,如今玩家的移动变得更加顺畅了。

使用Unity Remote进行调试

你可能会注意到,在最后的教程中基于iOS设备测试项目有点麻烦。导出到Xcode项目与在设备上创建和运行过程需要我们花费一定的时间,而这些都包含在开发过程中。

不过也存在一些更有效的方法。最快的调试方法便是使用名为Unity Remote的应用。这一应用让你能够略过多个步骤,如面向iOS创建项目,启动Xcode并在你的设备上运行。

基于Unity Remote iOS应用,我们可以将自己的iOS设备与Unity Editor连接在一起,并从iOS设备上去控制Unity Editor。这能让你在Unity Editor上快速调试游戏。

在App Store上购买Unity Remote是免费的。

注:如果要使用Unity Remote,你的iOS设备和计算机必须使用同一个Wi-Fi网络。除此之外,Unity Editor窗口还必须保持前台操作。如果你将Unity Editor窗口转向后台,你便会收到“等待游戏视图。按压‘播放’”的信息。

在Unity Editor上点击“播放”。在你的iOS设备上启动Unity Remote应用。从出现的列表中选择你的计算机。如果你的计算机并未出现在列表上,那就在Unity Remote的IP设置上输入计算机的IP地址。

list(from raywenderlich)

list(from raywenderlich)

当Unity Remote与你的计算机匹配在一起时,你的iOS设备便能够在Unity Editor上控制游戏的运行了。虽然设备显示器的分辨率不是最理想的,但这却是创建游戏原型的快速方法。当然,你也想偶尔面向iOS创建项目并通过Xcode发行,所以你可以基于更加现实的情境去测试游戏。

基于iOS测试游戏。你会发现,因为在iOS中并不存在向左/右/上/下输入,所以你不能在设备上移动玩家(游戏邦注:但是你却可以在Mac上进行控制)。接下来你将执行一些操纵杆控制去解决这一问题。

双重操纵杆,双重乐趣

幸运的是,Unity的标准资产包(包含资产)能够执行操纵杆函数。我们需要选择Assets\Import Package\Standard Assets (Mobile)从资产包中导入相关道具(如下所示)。

importing package(from raywenderlich)

importing package(from raywenderlich)

选择与操纵杆函数相关的指示道具。点击Import。在完成导入后,项目视图将包含名为Standard Assets (Mobile)的新文件夹。在带有导入操纵杆脚本的Untiy 4中你将看到如下警告:

warning(from raywenderlich)

warning(from raywenderlich)

为了解决这一问题,让我们双击警告内容。如此便会打开操纵杆脚本文件。将鼠标放在警告行上:

gameObject.active = false;

修改声明为:

gameObject.SetActive(false);

现在当你回到Unity Editor时,你会发现警告已经消失了。

首先在场景上添加Dual Joysticks预制件。预制件可以再次利用,并总是被定制为GameObject。我们可以从项目视图拖出预制件或经由脚本将其添加到场景中。例如,我们可以先创建一个代表玩家的预制件,并添加多个玩家到场景中。

在你的项目视图中打开Standard Assets (Mobile)\Prefabs文件夹。将Dual Joysticks预制件拖到层次结构视图中。

hierarchy view(from raywenderlich)

hierarchy view(from raywenderlich)

我们可以点击游戏标签并进入游戏视图看到操纵杆:

game view(from raywenderlich)

game view(from raywenderlich)

让我们回到场景视图中。

在层次结构视图中点击Dual Joysticks旁边的三角形。我们可以注意到Dual Joysticks GameObject包含了两个孩子GameObjects。

这个过程就像是“养育”过程,能够用于设置操纵杆父母/孩子GameObject之间的关系。如果你想要创造一个复合的GameObject(拥有连接GameObject),那么“养育”过程便非常有帮助。举个例子来说吧,如果你想要左右操纵杆同时发挥作用,那么当它们都被当成单一对象时,你便能够通过脚本轻松实现这一过程了。

选择LeftJoystick GameObject,并注意到它附加了操纵杆脚本组件,选择RightJoystick GameObject进行同样的核查。

操纵杆可以查出GUI Texture上的碰触事件,并基于某些限制条件去改变它的位置。例如,我们只能在特定范围内移动图像。脚本将确保位置输出的规范化,即保持在-1至+1的范围内。如此我们便能在iOS环境中使用操纵杆去替代Input.GetAxis()。

这时候你已经在场景中放置了2个操纵杆,但是它们却不能连接到Heroic Cube去触发输入内容。我们将修改脚本去分配操纵杆的任务,即右边操纵杆能够旋转玩家,而左边操纵杆将前后移动玩家。

修改MoveAround脚本去处理操纵杆的输入内容。打开脚本进行编辑,并添加两个代表移动和旋转操纵杆的公共变量:

var moveJoystick : Joystick;
var rotateJoystick : Joystick;

然后添加一个新函数,即面向操纵杆的位置并回到输出范围(在-1至+1之间)。将其添加到 Update()函数之后:

function joyStickInput (joystick : Joystick) {
var absJoyPos = Vector2 (Mathf.Abs(joystick.position.x),
Mathf.Abs(joystick.position.y));
var xDirection = (joystick.position.x > 0) ? 1 : -1;
var yDirection = (joystick.position.y > 0) ? 1 : -1;
return ( ( absJoyPos.x > absJoyPos.y) ? absJoyPos.x * xDirection : absJoyPos.y * yDirection);
}

操纵杆输入是一个Vector2输入,拥有x和y组件。我们可以使用更大的x或y绝对值去设置输出内容。我们还可以将操纵的方向作为倍增器去指示负值或正值。结果便是输出值的范围也是在-1至+1之间。

修改Update()函数去处理来自Unity Editor或iOS设备的输入内容:

function Update () {
var controller : CharacterController = GetComponent(CharacterController);

// Rotate around y – axis
var rotatePos = Input.GetAxis (“Horizontal”) ?
Input.GetAxis (“Horizontal”) : joyStickInput(rotateJoystick);
transform.Rotate(0, rotatePos * rotateSpeed, 0);

// Move forward / backward
var forward = transform.TransformDirection(Vector3.forward);
var movePos = Input.GetAxis (“Vertical”) ?
Input.GetAxis (“Vertical”) : joyStickInput(moveJoystick);
var curSpeed = speed * movePos;
controller.SimpleMove(forward * curSpeed);
}

变换的Rotate()函数将接受左/右箭头(或A/D按键)或旋转操纵杆的输入。角色控制器的SimpleMove函数将获得来自上/下箭头(或W/S按键)或左操纵杆的输入。

保存改变后的脚本。选择玩家GameObject(立方体)并注意Move Around脚本组件拥有两个关于移动操纵杆和旋转操纵杆的全新公共变量。

move around(from raywenderlich)

move around(from raywenderlich)

目前这些变量并未得到分配。我们仍需要选中玩家GameObject,并将LeftJoystick GameObject拖到Move Joystick变量。将RightJoystick GameObject拖到Rotate Joystick变量。(或者我们也可以使用每个变量旁边的选择器。)

move around(from raywenderlich)

move around(from raywenderlich)

点击Unity Editor的“播放”,并在我们的iOS设备上开始进行Unity Remote。

测试操纵杆函数并核实我们是否能使用左操纵杆向前或向后移动,并使用右操纵杆向左和向右移动。当我们在iOS设备上移动操纵杆时,我们也应该能够看到操纵杆在Unity Editor上移动。

unity editor(from raywenderlich)

unity editor(from raywenderlich)

注:也许你看到的操纵杆图像如图所示。但是不要担心,在真正的设备上出现的操纵杆并不是这样。

清晰明亮的天空盒

如今我们已经完善了Heroic Cube的移动,接下来是否该完善场景呢?到目前为止玩家一直待在一个阴暗的世界。我们应该想办法去美化游戏环境。

幸运的是这并不困难。Unity包含标准资产包中的资产,我们可以使用这些资产去创造天空,添加植被并改变地形的高度。

在这一阶段你将利用天空盒组件去添加天空。天空盒是一个较大的立方体,能够附加到游戏的Main Camera上。当你添加了组件时,你便能够添加材料去装饰它,并经过渲染而创造出天空的效果。

选择Assets\Import Package\Skyboxes开始输入过程。选择Sunny2 Skybox.mat,然后点击Import。

importing package(from raywenderlich)

importing package(from raywenderlich)

在完成输入后,你的项目视图将拥有一个全新的Standard Assets\Skyboxes文件夹,即包含最新输入的资产。

project(from raywenderlich)

project(from raywenderlich)

选择Main Camera对象,然后选择Component\Rendering\Skybox。

smooth follow(from raywenderlich)

smooth follow(from raywenderlich)

新组件将出现在Inspector。我们可以注意到新组件包含一个代表材料的变量。在此你所输入的天空盒材料便能发挥作用了。

点击Custom Skybox变量旁边小小的圆形图标。这时候将弹出Select Material对话框,其中列出了一些你的项目可以使用的材料资产。

select material(from raywenderlich)

select material(from raywenderlich)

现在场景视图将发生改变,即呈现出我们所添加的明亮天空。我们可以点击游戏标签去观看游戏视图中的天空,或编辑“播放”按键。

smooth follw(from raywenderlich)

smooth follw(from raywenderlich)

太阳也出现了!尽管有时候会出现阴天,但是我们也可以添加一些绿色植物为游戏世界增添色彩。

scene(from raywenderlich)

scene(from raywenderlich)

不要忘记植物

让我们回到场景视图。我们可以添加地形GameObject而创造植被,然后添加材料(如草地)和对象(如树木)。

这时候我们将不再需要平面GameObject,因为地形将负责铺设层面。右击层次结构视图的平面GameObject,然后选择删除。

选择Assets\Import Package\Terrain Assets。

importing package(from raywenderlich)

importing package(from raywenderlich)

点击Import去输入所有选择。这时候地形资产将出现在标准资产文件夹中。我们可以使用已经输入的资产去修改地形GameObject的行为。

选择Terrain\Create Terrain将地形GameObject添加到场景中。选择地形对象并使用Inspector将其参数域改为-1000,0,-1000。这将最大限度地延伸地形,从而提供给玩家足够广的移动空间。

terrain(from raywenderlich)

terrain(from raywenderlich)

Terrain (Script)所包含的工具能够帮助我们装饰地形:

terrain script(from raywenderlich)

terrain script(from raywenderlich)

选择绘画工具中的画笔:

paint tool(from raywenderlich)

paint tool(from raywenderlich)

我们将能用草地去装饰地形。点击Edit Textures\Add Texture:

grass(from raywenderlich)

grass(from raywenderlich)

在Add Terrain Texture对话框的纹理区域中点击“选择”,选择Grass (Hill)纹理,关闭弹出的Select Texture2D,然后选择“添加”:

terrain script(from raywenderlich)

terrain script(from raywenderlich)

点击场景然后开始绘制草地。检查原图,然后点击游戏标签:

grass scene(from raywenderlich)

grass scene(from raywenderlich)

如果只是进行景观美化便非常简单!

回到场景视图–现在我们便能够种植一些棕榈树了。在Terrain (Script)中选择“种树”工具:

terrain script(from raywenderlich)

terrain script(from raywenderlich)

点击Edit Trees\Add Tree:

add tree(from raywenderlich)

add tree(from raywenderlich)

在添加树的对话框中点击树旁边的圆形图标,选择Palm GameObject,然后点击“添加”:

terrain script(from raywenderlich)

terrain script(from raywenderlich)

将笔触大小设置为20:

brush size(from raywenderlich)

brush size(from raywenderlich)

然后我们便可以点击适当的位置去添加树了。提示:放大场景并着眼于我们想要种树的位置。在添加树的过程中尝试着调整电光源的范围和高度去浏览更多场景。

point light range(from raywenderlich)

point light range(from raywenderlich)

完成这些设置后你的场景将如下图所示:

scene textured(from raywenderlich)

scene textured(from raywenderlich)

已经很棒了!渐渐有了真实世界的雏形了。但是地形看起来还是很平坦。

这时候我们可以在地形中添加一些高度变量。在Terrain (Script)中选择最左边的工具去提高或降低地形的高度:

terrain script(from raywenderlich)

terrain script(from raywenderlich)

将笔触大小设置为20,然后在场景视图中围绕着玩家点击2至3个点(不要靠太近)以变化地形的高度。

scene textured(from raywenderlich)

scene textured(from raywenderlich)

预览游戏并在场景中移动。适当调整场景中树的数量,并记得在做出任何改变之前暂停游戏。

tree(from raywenderlich)

tree(from raywenderlich)

保存场景。

使用Unity Remote去测试项目,当你感到满意时便能够将其作为一个Xcode项目。选择File\Build Settings,在构建设置的对话框中点击Add Current去添加Level_2场景。新场景将出现在Scenes In Build列表上。这是取消Level_1场景的选定而至创建Level_2。

settings(from raywenderlich)

settings(from raywenderlich)

点击建造,必要的话选择替换之前的项目,然后启动Xcode项目。在我们的iOS设备上调配并测试。

iOS device(from raywenderlich)

iOS device(from raywenderlich)

本文为游戏邦/gamerboom.com编译,作者:Christine Abernathy)


Beginning Unity 3D for iOS: Part 1/3

by Christine Abernathy

Unity is one of the most popular game engines these days. And for good reason – Unity has a powerful visual editor that makes it very easy to get started, a ton of power and functionality, a great community, attractive pricing, and more!

If you’ve been eager to try out Unity for yourself, look no further than this tutorial! In this tutorial you’ll learn how to create a simple iOS game with Unity – and no prior experience is required!

The simple game you’ll create in this tutorial will challenge the player to get to a finish line within a certain time limit while avoiding obstacles along the way.

Along YOUR way, you will be introduced to the Unity development environment and workflow, and learn (or review) the basic concepts of game design.

The tutorial will be split into three parts:

In Part 1, you’ll learn the basics of using Unity by creating a game with a simple player control mechanism. You’ll also learn how to deploy your project on iOS.

In Part 2, you’ll learn how to enhance the player’s movements using pre-built controller objects and some scripts found in the standard packages, how to debug using Unity Remote, and how to customize the scene.

In Part 3, you’ll add gameplay to your project and build on game design concepts that include adding prefabs, timers, menus and sounds to enrich the game experience.

Ready to add a powerful new framework to your skillset? Keep reading on! :]

Getting Started

As you move through this tutorial series, you’ll start to become familiar with the Unity development workflow, which has four basic components:

Assembling your game scene in the Unity Editor.

Scripting using the MonoDevelop Editor.

Remote debugging with Unity Remote.

Publishing to your iOS device through the Unity Editor.

In this first part of the tutorial, you’ll install Unity, learn the basics of the Editor interface, and create a project that introduces you to the basic game concepts.

By the end of Part 1, your game will have a player that is able to move via touch triggers. You’ll also test your project in the Unity Editor and with an iOS device.

This tutorial uses Unity version 4 – so go ahead and download Unity if you don’t have it already.

Unity’s doffers a free 30-day trial of the full version of Unity Pro. This version of Unity will allow you to develop games and build them to run on iOS. Although Unity is available for both Mac and Windows, this tutorial is written based on the Mac environment.

Note: The Unity software package is a fairly hefty one at close to 1GB and, depending on your Internet connection, it might take a while to download. So download the file in advance if you want to get going immediately.

Create the Project

Once you’ve downloaded Unity and installed it, launch the Unity application. If this is your first time launching Unity, you will be prompted to activate your copy. Select the option to activate the free 30-day trial of Unity Pro, as shown in the screenshot below:

Then you will need to create a Unity account if you do not have one, confirm your e-mail address, and login to your account via the Unity app.

Once you login, you’ll be asked to answer a few questions. You can skip them if you scroll to the very bottom of the list and tap “Not Right Now.” :] And then, finally, you can start using Unity.

At this point you should be presented with the Unity interface with a default project already in place – something like the following:

Discard that project and create a fresh project by selecting File\New Project from the menu. You’ll be presented with the Project Wizard:

In the Project Wizard, click Set and navigate to the folder where you wish to save your project. Enter DashAndZag for the project name and click Save, then Create Project. (You will be asked whether you want to save the previously open default project, but you can opt not to do so, unless of course you want to save it for some reason…)

Note: The Project Wizard includes some standard packages you can import during the initial project creation. Ignore this for now. You’ll import any packages you need for this tutorial later on.

Unity will close the current project and re-launch with your new project:

Ah, a fresh canvas! But what are all these controls, windows and tabs? Where to start?
Getting to Know UI…

It’s worth taking some time to get real cozy with the Unity Editor interface, so take a look around. The first stop on your tour is the Editor Layout tab in the upper-right corner. Change the view to Wide mode:

Here’s a breakdown of what you see, with the various sections highlighted:

Project View: Your Unity project contains an Assets folder whose contents are shown in this section. This is where the scripts, scenes, prefabs and other Unity objects that you create show up.

Hierarchy View: This contains the GameObjects that are in the current scene. Every object that shows up in a Unity game is known as a GameObject. These could be simple objects that you create from the GameObject menu or assets you import. Your initial project will contain one GameObject: the Main Camera.

Toolbar: The toolbar allows you to manipulate objects in the Scene View or Game View, to control how your Editor views are displayed and to control the game preview in the Editor.

Scene View: This view is where you position your GameObjects to set up your game. The Scene View contains a Scene Gizmo (the thing in the top-right corner with the marked axes) that displays the scene camera’s current orientation.

Game View: This is the view of your game from the camera(s) in your game. You’ll be brought to the Game View when you hit the Play button in the toolbar. Alternatively, you can switch between the Game and Scene views using the tabs at the top of the window.

Inspector: This provides further details about a selected GameObject. You can then modify the object’s properties such as its size or position, or attach scripts to modify the GameObject’s behavior.

You’ll want to be very comfortable using the toolbar transform tools to position GameObjects and navigate around in the Scene View. So let’s dive into that next.

Getting a Hand

The Hand Tool allows you to manipulate your view of the scene.

The best way to understand the Hand Tool’s use is to imagine yourself dropped into the 3D scene with many GameObjects. Some objects in front of you are visible, while others that are behind you are not.

You may wish to step back in the scene (zoom out) to see more of the view, move to the left or right to see other objects, or swivel and pan around to see what’s behind you. The Hand Tool can do this for you.

As you start to add more GameObjects, you’ll find yourself using this tool more and more to establish your view in the scene before positioning GameObjects.

To see the Hand Tool in action, first select it (left-most choice on the toolbar), then select the Main Camera from the Hierarchy View (just so you have something to look at in the Scene View). You can then drag the canvas to move around the scene.

To zoom, you can use your mouse wheel or hold down Control and drag. You can rotate by holding down option and dragging. If you want to reset your view at any time, you can click on one of the axes on the Scene Gizmo in the upper right.

Play around with the hand tool a bit and get comfortable with moving around and using the Control and Option combinations to zoom/rotate.

You’ll be switching between the hand tool and other tools a lot, so it helps to remember its shortcut keys. By default, the keys are bound to the keys on the upper left of your keyboard – Q, W, E, and R for Hand, Move, Rotate, and Scale, respectively.

Note: The Hand Tool does not move objects. It only alters your view of the scene, so it may appear as if the objects are moving. Practice moving around the scene using the various Hand Tool options.

Move It Or Lose It

With the Move Tool, you can move GameObjects in 3D space.

Select the Main Camera (double-click it in the Hierarchy View if you don’t see it in the Scene View) and click on the Move Tool. You should see a gizmo around the Main Camera with arrows representing the three axes. These point to where you can move the object:

The red arrow represents the x-axis, the green arrow the y-axis, and the blue the z-axis. You can translate or move a GameObject by first selecting the object, left-clicking, and then dragging inside the gizmo (the cube portion).

Select the Main Camera and move it around. Take a look at the Inspector’s transform component. The Position section has x, y, and z values representing the GameObject’s position. As you move the object around, notice that these values change.

You can change a GameObject’s transform position using either the Move Tool or by typing the position you want directly into these fields.

If you wish to move a GameObject in only one direction, select the relevant axis in the gizmo, left-click and drag that axis. Test this with the Main Camera object by moving in only the x direction and checking that only the x-position value changes in the Inspector. Repeat the same test with the y and z axes.

At this point you know how to move your personal view of the scene around, as well as how to move objects around. So far so good!

You Spin Me Right Round

The Rotate Tool allows you to rotate GameObjects in 3D space.

To understand the Rotate Tool and how to use it, it’s useful to discuss the Scene Gizmo in more detail. The Scene Gizmo is found on the top-right of the Scene View and has different modes for different views.

One mode (shown in the below right image) is the free-form view that enables you to view your scene in a 3D perspective.

This is useful if you want to get a better representation of what your game looks like in 3D space.

You can click on the text under the gizmo to switch to an isometric view (shown in the below left image). This mode is useful in visualizing a GameObject when it’s being rotated.

Another mode is the x-axis view, which enables you to view your scene as if you’re looking down the x-axis. This is useful if you want to move a GameObject along either the y- or z-axis while keeping the x-axis unchanged:

In a similar fashion, you have the y- and z-axis view modes to enable the view of the scene from those respective axes:

Select the Main Camera. Switch to the free-form perspective mode by right-clicking on the gizmo and selecting Free.

Then click on the text below the gizmo to switch between the isometric and perspective modes. Click on the x-, y-, and z-axis modes in turn to see how the Scene Gizmo and Scene View change.

Select the free-form view once more to test out rotation. With the Main Camera still selected, click the Rotate Tool. You should see a gizmo around the Main Camera containing circles with colors representing the three rotation axes:

Left-click in the center of the Main Camera and use your mouse to drag-rotate it around. Note that the Inspector’s Transform\Rotation properties change as you rotate the object. Note that you can manually edit these values in the Inspector if you’d like.

By clicking in the center of the Main Camera during rotation, you are doing a free-form rotation around all axes. You can also rotate the GameObject around one axis by clicking on one of the colored circles representing that axis. For example, to rotate only around the x-axis, click the red circle to select it, then hold and drag to rotate the object. Repeat the same process to rotate around just the y or z axis.

It All Comes Down to Point of View

Another key concept worth learning at this point is the difference between the local and global (or world) view.

Reset the Main Camera’s rotation to 0,0,0 through the Inspector\Transform\Rotation fields. Click the button so the toolbar says “Local”. Then select the Move Tool so you can see the Scene Gizmo:

Notice that the Scene Gizmo and the Main Camera’s Gizmo line up, in the sense that the x-axes point in the same direction, as do the y- and z-axes. Now rotate the Main Camera around on the z-axis using the Inspector by setting the Transform\Rotation value to 0,0,-20.

Notice that the Main Camera’s Gizmo is now rotated around the z-axis – this represents the axis of the object in its local coordinates. This is different compared to the Scene Gizmo, which shows the global space orientation. Switch to Global view to see the difference.

Later in the tutorial, you’ll learn about moving GameObjects and find that it matters which space (world or local) you specify for the movement to use.

Taking a look at the rotated Main Camera, if you were to now move it in the x-direction based on its local space view, it would end up in a different place than if you were to move it in the x-direction based on the global space orientation. Keep that nugget tucked in your mind for later use!

Before you move on, reset the rotation to 0,0,0 to get back to a clean slate.

Scale Tool

The Scale Tool allows you to, you guessed it, scale GameObjects up or down in size.

As with the other GameObject manipulation tools, you can make your changes along only one of the three axes, and you have the choice of modifying the Inspector\Transform component instead of using the tool.

Select the Main Camera and note that the Scale Gizmo consists of cube handles at the end of each axis and one at the center.

To scale freely across all axes, select the cube at the center of the object and left-click, then move up to make the GameObject bigger and move down to make it smaller. Take a look at the Inspector\Transform\Scale properties. You should see the numbers go up or down as you grow or shrink the object.

Test scaling along the x-axis by selecting the red gizmo handle for the x-axis, and holding and then moving the handle outward. Verify using the Inspector that the Transform\Scale x-value is the only one that changes. Try this with the y and z axes as well.

Once you’re done playing around with the controls, reset the Main Camera to the following settings using the Inspector\Transform section:

Position: 0,1,-10
Rotation: 0,0,0
Scale: 1,1,1

Your Transform menu should look like this:

You will learn about the other Editor interface components as you walk through the tutorial. This includes previewing a game using the Play button and using the Unity debugger.

Lonely No More: Adding GameObjects

Now that you’ve run through the basic concepts, you’re ready to begin adding GameObjects to keep the camera company – it’s been pretty lonely all by itself :]

Right now the camera is looking out on a very desolate world. Never fear – get ready to add a cube GameObject that represents the player, as well as a plane GameObject that represents the floor the player will move upon.

When you’re designing a game with Unity, a best practice is to first develop the gameplay without any fancy assets that represent the player. That way, you can concentrate on optimizing gameplay and player movements without being distracted by graphics.

Another point to note is that Unity is a very good game engine, but you don’t want to use it to create graphic assets. There are many tools out there that are wonderful in the graphics department and Unity is adept at importing assets from a wide range of tools.

Often, the typical division of game development labor is that the game developer works on the gameplay using Unity while the graphics designer creates assets in parallel using their favorite graphics tool. The two converge down the line when it makes sense to bring in the graphical assets to polish up the game.

Now that you’ve got that to think about, let’s get shaking! Add the floor GameObject, represented by a plane, by selecting Game Object\Create Other\Plane.

The new plane GameObject should appear in the Hierarchy View. Select the plane in the Hierarchy View and set Transform\Position to 0,0,0 using the Inspector. Also use the Inspector to scale it up to 50,1,50. Your scene should look something like this:

Next you’ll add the player GameObject, which in your game will be represented by a cube. That’s right, the Heroic Cube!

Select Game Object\Create Other\Cube, and the new cube GameObject should appear in the Hierarchy View. Select the cube in the Hierarchy View and set the Transform\Position to 0,0,0 using the Inspector. Your scene should look like this:

Click on the Move Tool, then click the y-axis in the Scene Gizmo to constrain the object’s move to only the y-axis. Move the Heroic Cube up a little so it’s above the plane (floor). You can also set the transform position to 0,1,0 to move the Cube up a little.

Now comes an exciting moment – click the Play button on the Unity Editor toolbar (at the top) to preview your game thus far:

You’re now testing your game using the Unity Editor. The Editor should switch to the Game View and you should see something like this:

What you’re seeing is a view of the game through the Main Camera in your scene. Your player, the Heroic Cube, is shown in the distance, above the floor – alone in the world, but bravely present!

There’s not much going on in the game because you haven’t added any components to modify the player’s behavior. It’s also a little dark in this scene. You can take care of the latter issue first by adding a light source to your scene.

Stop the game preview by clicking on the Play button again. Back in the Scene View, add a light source. Select Game Object\Create Other\Point Light. As usual, move the light to the origin before making further adjustments to its position. Set the transform position to 0,0,0 using the Inspector.

Now adjust the light’s height and brightness so you can see more of the scene. Here’s a hint: use the Move Tool and constrain movement along the y-axis only.

To adjust the brightness, modify the Range and Intensity settings in the Light component. Make use of the Hand Tool to swivel around if you need to get a better view of the scene.

A good way to see if you have enough light is to switch to the Game View using the Game tab (rather than hitting the Play button). Go back and forth until it looks like you can see your player:

After you’ve made your adjustments, hit the Play button again to verify your changes. Your view should be similar to the following when you switch to the Game View:

Congrats, you’ve added all the GameObjects you need for this stage of the tutorial! Remember, as a good practice you are focusing on gameplay first, then adding graphics later.

Since you’ve done something meaningful, go ahead and save your work as a scene in the project. A project can be made up of one or more scenes. You can think of a scene as the equivalent of a level in a game.

In this tutorial, you’ll represent each part of the tutorial as a scene. This is an artificial concept of a game level, but it allows you to reuse assets from one scene in the next.

To save the scene, select File\Save Scene and in the Save Scene dialog, name your scene Level_1. Your Project View should update with the scene you’ve just created.

Get Moving: Event Functions

The game is currently way too static! It’s in dire need of movement to make it come alive.

You can add movement by creating your own scripts or using pre-packaged scripts that you attach to the relevant GameObject to perform an action. For example, in Part 1 of this tutorial, you’ll create a script that moves the player when touched. The script you create needs to respond to touch events to change the Heroic Cube’s position and rotation.

Unity supports these languages for scripting: JavaScript, C#, and Boo. In this tutorial you’ll be using JavaScript. Unity’s scripting language includes pre-defined event functions that you can use to help define the GameObject’s behavior.

The event function that you’ll use the most is the Update() function. If you define this function in your script, it will be called once per frame. Your game display is drawn once per frame and the Update function will therefore be responsible for the display during a particular frame.

A game runs at a certain amount of frames per second and one thing to keep in mind is that this rate may vary depending on the Platform on which the game is being run, and on how tied up the OS resources are by other applications. This means you shouldn’t do anything very time intensive here, and you can’t assume that it is called at any particular rate.

Another pre-defined event function, FixedUpdate(), is called at a fixed rate independent of the frame rate. If your script defines this method it will be called at a fixed interval (in comparison to the Update method which can vary quite a bit from call to call).

You’ll want to process any physics-related work inside of a FixedUpdate() function, since physics work is very time sensitive. For example, you may have a GameObject that uses physics, such as RigidBody (you’ll learn more about this later). When this object collides with another object you may want to calculate the force to apply to the object, and you should do it in a FixedUpdate() function.

For operations like changing an object’s transform position or rotation, it’s perfectly fine to do this inside of an Update() function.

A third useful function is Start(), called before the first frame update happens. You’ll typically put initialization operations here.

Finally, the Awake() function is called when the game begins. It’s another good place to put initialization code.
The Right Touch

Let’s try this out. Create a new script by selecting Assets\Create\Javascript. A new script with the default name NewBehaviorScript should show up in your Project View. Click inside the script’s name in the Project View and rename it to MoveSimple.

Double-click on the script to open it. It should open in the bundled MonoDevelop Unity Editor and should contain the following code:
#pragma strict

function Start () {

}

function Update () {

}
The Start() and Update() functions have been stubbed out for you, as they are commonly used event functions. You won’t be needing the Start() function, so remove it. Add the following variables that you’ll use to control the Heroic Cube’s movement and rotation speed below the #pragma line:
var speed : float = 3.0;
var rotateSpeed : float = 10.0;
Replace the empty Update() function with the following:
function Update () {
// Detect mouse left clicks
if (Input.GetMouseButtonDown(0)) {
// Check if the GameObject is clicked by casting a
// Ray from the main camera to the touched position.
var ray : Ray = Camera.main.ScreenPointToRay
(Input.mousePosition);
var hit : RaycastHit;
// Cast a ray of distance 100, and check if this
// collider is hit.
if (collider.Raycast (ray, hit, 100.0)) {
// Log a debug message
Debug.Log(“Moving the target”);
// Move the target forward
transform.Translate(Vector3.forward * speed);
// Rotate the target along the y-axis
transform.Rotate(Vector3.up * rotateSpeed);
} else {
// Clear the debug message
Debug.Log(“”);
}
}
}
Save your changes.

This code first looks for mouse click events, specifically from the left mouse button. A parameter of “0″ signifies a left-click, “1″ a right-click and “2″ a middle-click when used with the GetMouseButtonDown function. If a click is detected, then the code constructs a ray (think of a laser pointer) from the Main Camera to the mouse click position.

The collider.Raycast() function detects if the collider attached to this script is hit by the ray. If the collider is hit, the collider.Raycast() call returns true. The function call takes in three arguments:

The ray you constructed.

A RaycastHit object, which will contain more details if the collider is hit.

A ray length argument.

Assuming a true result, the follow-on code then nudges the player forward based on the speed variable, as well as rotates the player based on the rotateSpeed variable. The transform.Translate() function moves the GameObject transform in the direction and distance specified by its Vector3 input.

Vector3 is a 3D vector representation of an object that has direction and a length or magnitude. The vector can be broken down into x, y and z components.

In the code, your Heroic Cube is moved in the forward direction at a distance multiplier calculated based on the speed variable. Vector3.forward is the same as Vector3(0,0,1) and a speed multiplier of 3 will move the Cube by Vector3(0,0,3).

The direction in which the player moves is relative to the player’s local space. To get a sense of this direction, select the Cube, then the Move Tool and view the z-axis direction. That’s the direction in which the player will move.

The transform.Rotate() function rotates the GameObject transform based on an angle specified by the Vector3 input. Euler angles are used to describe the orientation of a GameObject. In the case of a rotation, the object will be moved Euler angles z degrees around the z-axis, Euler angles x degrees around the x-axis, and finally Euler angles y degrees around the y-axis.

In the code above, the player is being rotated using Vector3.up or Vector(0,1,0), which represents movement around the y-axis. The rotation angle is multiplied by rotateSpeed. The rotation is relative to the player’s local space. So your Heroic Cube will rotate around its y-axis, which, as you know, could differ from the global y-axis.

Note: A real game would never control a player using these types of movements. They are used here simply to illustrate the basic concepts involved in moving GameObjects and will be replaced with more realistic movements in the upcoming parts of the tutorial.

The code contains two Debug.Log() statements. The log output is printed in the Unity console when the game is running. You can see the last log output at the bottom of the Unity Editor. You can also open up the console by selecting Window\Console to see previous log output, as well as clear the logging.

You’ll want to keep an eye on log output at the bottom of the Unity Editor, as that’s where any script errors you have are displayed.

Now that you’ve defined a behavior via code, you can assign it to a GameObject. Select the Cube in the Hierarchy View, then select Component\Scripts\Move Simple. This step is called adding a script behavior to a GameObject and you are simply selecting the script (named MoveSimple) that you already created.

Notice that the Inspector now contains a Move Simple script section. The public variables you defined in code, speed and rotateSpeed, are visible in the Inspector View. You can now modify these public variables for just the attached GameObjects without changing the underlying script.

This means if you had two players in the scene with the MoveSimple script attached to them, you could make one player move faster than the other by increasing the speed value via the Inspector\Move Simple\Speed field.

Click Play to preview the game. Touch the player one tap at a time and pay attention to the changes in the transform position and rotation properties in the Inspector.

Notice that the transform position that started at 0,1,0 has changed to 0,1,3 – in other words, there’s been a translation movement in the z direction of 3 due to the speed multiplier. The rotation has also changed from 1,1,1 to approximately 1,10,1, which closely matches the rotateSpeed multiplier.

While the game is running, you can change the speed and rotate speed variables in the Inspector. Increase the speed and watch the transform position after clicking on the player.

Stop the game and notice that the speed and rotate speed variables are reset to their original values. Any changes you make while playing the game are temporary. This allows you to tinker around with various settings and come back to the original settings when you’ve completed your preview. If you then want to make lasting changes, you can do so before testing the game again.

Note that as you play the game, the console logs the correct debug statement, depending on whether or not the player is clicked.

Get It All On Camera

You’ll likely have noticed that as you move the Heroic Cube, it moves further and further away from the camera – not a good feeling. Like a well-meaning parent with an ambitious toddler, you’ll modify your game to have the Main Camera track the player at a fixed position from behind. This is typical modus operandi for third-person shooter games.

Select Assets\Import Package\Scripts and in the Items to Import section, choose only the SmoothFollow script and click Import:

Note: If you don’t get the import selection dialog when you select Assets\Import Package\Scripts, then try quitting Unity and restarting. That worked for me. :]

A new Standard Assets folder should show up in your Project View. If you navigate through its subfolders you should eventually see a SmoothFollow script. Double-click the script to open it in MonoDevelop so you can look through the key portions of code.

var target : Transform;
The above represents the public variable for the target being tracked. The target’s transform info is used to set the follower’s (or Main Camera’s) position and rotation.

The follower’s position and rotation are set in LateUpdate(), another pre-defined event function. This function is called just after the Update() function completes, and is typically where you would put code that has a dependency on operations that happen in Update().

Once the Heroic Cube’s position and rotation are changed in the Update() defined in the MoveSimple script, the camera can update its own position and rotation in the LateUpdate() of the SmoothFollow script.
..
var wantedRotationAngle = target.eulerAngles.y; // 1
var currentRotationAngle = transform.eulerAngles.y;
..
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
..
var currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);

..
transform.position = target.position; // 2
transform.position -= currentRotation * Vector3.forward * distance;
transform.position.y = currentHeight;
..
transform.LookAt (target); // 3
..

Here are the key points for the above code sections:

Find the angle to which the follower needs to rotate, to match the target rotation. The rotation is around the y-axis.

Move the follower behind the target by an offset corresponding to the distance variable. Also rotate the follower around the y-axis using the results from #1. Finally, make sure that the follower ends up at a fixed height above the target.

Ensure that the follower is always facing the target.

Now attach this script to the Main Camera. Select the Main Camera in the Hierarchy View, then select Component\Camera Control\Smooth Follow:

Verify that a new section for Smooth Follow is added to the Main Camera’s Inspector.

Note that the Target variable is unassigned at this point and has None next to it. You’ll want to assign the Cube GameObject to this input. While the Main Camera is still selected and the Smooth Follow script visible in the Inspector, drag the Cube GameObject from the Hierarchy View to the Target variable. Alternatively, you can tap the little circle with a dot in the center next to the Target value to get a list of objects from which to select.

The Target variable should now be linked to Cube (the player).

Click the Play button. You should immediately see a change in the view, as you’re now looking down at the player from a given height. Click on the player to move it, and watch how the camera tracks the player. Pay attention to the Main Camera’s transform info in the Inspector and observe it change as the Heroic Cube moves.

Stop the game, and save the scene before moving on to the next step.

Deploying on iOS

If you’re like me, you can’t wait to see how this works on an iOS device. The good news is that the trial version of Unity Pro allows you to test your project on iOS!

It’s a best practice to test your Unity projects on an actual device (i.e. not the Simulator). You don’t want to limit your testing to just the Simulator, even though you can do that. Since game development relies so much on the underlying hardware, you want to test on a real device as soon as you can to find any performance issues early.

To deploy to an iOS device, you need to be a registered Apple developer with device deployment capabilities. If you haven’t already, go ahead and fork over the $99 – we’ll be right here waiting for you.

Unity can build your game as an Xcode project that you can deploy to an iOS device. To set this up, select File\Build Settings:

Select the iOS platform and click Switch Platform. Then click on the Player Settings button found at the bottom of the Build Settings dialog. Unity Editor’s Inspector should now display Player Settings that you can customize for your iOS deployment. Make the following changes:

Resolution and Presentation

Default Orientation: Landscape Left

Other Settings

Bundle Identifier: the Bundle Identifier needed so that your app can be properly built on your device.

SDK Version: Device SDK

Target iOS Version: 4.3

Go back to the Build Settings dialog. Add the scenes that will be part of the iOS build in the Scenes In Build section. Since you only have one scene in your project, this is a no-brainer. Add the Level_1 scene by clicking the Add Current button.

Click the Build button to initiate the build process. You’ll be asked to specify a location to save the Xcode project. Navigate to where you want to save your Xcode project, enter DashAndZag in the Save As field, and select Save.

Unity will now build the project and open the folder that contains the Xcode version. The project will have the name Unity-iPhone.xcodeproj.

Open the project using Xcode, make sure that the scheme is set to Unity-iPhone, select your device, and build the project.

Run the app. You should first see a splash screen with the default Unity logo. Then, your game should come up:

Touch the Heroic Cube and watch it move around. You’ve just built and deployed your first Unity project on iOS!

One Finger to Rule Them All

But wait, you’re not done yet!

If you play the game a bit longer, you’ll notice something odd. You can move the Cube by touching it with one finger. However, the Cube will also move when you use two fingers placed at an equal distance from it. What’s going on?

Recall this line of code from your MoveSimple script:

var ray : Ray = Camera.main.ScreenPointToRay
(Input.mousePosition);

This casts a ray from the camera to the touch point. The touch point is represented by Input.mousePosition. When running on an iOS device, Input.mousePosition is calculated as an average position of all current touches. Placing your fingers so that the average falls on the player makes the player move!

You should fix this to avoid confusing the user. You can use touch-related functions available in Unity to detect touch events and find the position of a touch more accurately.

Open your MoveSimple script. Add a flag at the top (where the other variables are) that will indicate that you can use touch input:

private var isTouchDevice : boolean = false;
You’re doing this so you can test on both iOS and the Unity Editor. If you’re only going to test on iOS, then you can bypass the touch check logic and simply use the touch-related functions.
Next add an Awake() function that will perform a runtime check to detect if the game is running in an iOS environment. The Awake() function is called only once, when the game is loaded:
function Awake() {
if (Application.platform == RuntimePlatform.IPhonePlayer)
isTouchDevice = true;
else
isTouchDevice = false;
}

Application.platform returns the platform on which the game is running. RuntimePlatform.IPhonePlayer indicates that the game is running on iOS.

Finally, modify your Update() function as follows to handle touch input:

function Update () {

var clickDetected : boolean;
var touchPosition : Vector3;

// Detect click and calculate touch position
if (isTouchDevice) {
clickDetected = (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began);
touchPosition = Input.GetTouch(0).position;
} else {
clickDetected = (Input.GetMouseButtonDown(0));
touchPosition = Input.mousePosition;
}

// Detect clicks
if (clickDetected) {
// Check if the GameObject is clicked by casting a
// Ray from the main camera to the touched position.
var ray : Ray = Camera.main.ScreenPointToRay
(touchPosition);
var hit : RaycastHit;

Save your changes.

You are using two new local variables, clickDetected and touchPosition, to detect clicks and save the click position. If running on iOS, you detect the click by checking that a touch has just begun. Then you calculate the click position based on the position of the first touch. If you’re not running on iOS, the logic is the same as before.

Before rebuilding the project, close the Xcode project. Now, rebuild in Unity from the Build Settings dialog. If presented with a warning about the Build folder already existing, select Replace.

Once the Xcode project is rebuilt, open it and run the game on your iOS device. Verify that you’re able to move the Heroic Cube and that the wrinkle allowing you to move it with two fingers is now gone.

Where to Go From Here?

Congratulations, you’ve just finished learning the basics of developing with Unity and deploying on iOS! Here are some downloads with all of the code from the project up until this point: Unity Project, Xcode Project.

In the next part of the tutorial, you’ll build on this rudimentary game by enhancing the Heroic Cube’s movement and improving the scenery. You’ll also do a bit of debugging!

In the meantime, if you have any questions or comments about what you’ve done so far, jump into the conversation in the forums!(source:raywenderlich)


→如果您认为本词条还有待完善,请 编辑词条

词条内容仅供参考,如果您需要解决具体问题
(尤其在法律、医学等领域),建议您咨询相关领域专业人士。
1

标签: Unity 3D开发入门教程

收藏到: Favorites  

同义词: 暂无同义词

关于本词条的评论 (共0条)发表评论>>

对词条发表评论

评论长度最大为200个字符。