如何使用unity3d简单游戏制作制作游戏

Unity3D游戏开发入门教程
授课讲师:
软件版本:
Unity3D 4.2英文版
教程程度:
所需基础:
C语言基础或其他编程基础
交流提问:
适合人群:
游戏开发爱好者
相关素材:
课程光盘:
3441 353067 185396 265951 183633 129563 112074 124322 111015 84962 72959 56324 83436 108581 56909 49051 45997 43627 45722 43419 39603 41753 48568 36690 26685 27525 34464 38977 32755 34816
论坛最新主题
您可能感兴趣的课程
针对全国计算机等级考试二级的一套精品视频教程
access是一套关联式数据管理系统,存储方式简单、界面友好、易操作。
通过太空射击游戏等案例设计过程,使学员掌握程序设计技巧和方法。
塔防类3D游戏开发过程入手,学习资源整合,程序设计并最终发布游戏。
赞助商链接
兴趣圈成员用unity3d制作2.5D游戏详细教程二
In the first part of the tutorial series, we covered the basics of using Unity and writing scripts with C#. We created a simple game where a plane could fly back and forth bombing sharks while protecting the clown fish!
In this second and final part of the tutorial series, we&re going to extend the game to add some finishing touches. We&ll add some sound effects and music, wrap up the game logic, and add multiple scenes to the game!
If you don&t have it already, grab the project where we left it off in the last tutorial, and open it up in Unity. Make sure to click the Scenes\LevelScene item to make it visible if it doesn&t load on startup.
Allright, so let&s learn some more about Unity and wrap up this game!&
Adding iCandy to the game
You&ve probably noticed that when a bomb hits a shark, it just quietly disappears, and thought to yourself, &meh, that&s not very cool!&
Well, be prepared to be blown away & we&re going to add a cool underwater explosion instead!
From the menu select &GameObject/Create other/Particle System&, and you&ll see a particle system appear on the scene. Rename the &Particle System& to &Explosion& in &Hierarchy& panel, and set the Explosion&s position to [1, 1, 8].
Now if you are a Particle System specialist & head to the &Inspector& and pimp it up yourself, and if you are not & just follow my lead it&s pretty easy. Copy over these values in the &Inspector&:
Here the most important property is &One shot& & when you check it the system will emit particles only once & as an explosion does. Now let&s setup also the animation values & just try to more or less match the colors below (not important if you don&t):
Here the one important property is &Autodestruct& & when checked the Particle System will remove itself from the scene when there are no more living particles. This is exactly what we want & it&s like automatic garbage collection.
Now you have a nice small explosion and you need to do exactly the same you did before with the bomb & make a prefab, instantiate it when needed, leave it to autodestroy itself when it&s done on the scene.
Right-click &Project& panel &Prefabs& folder, choose &Create/Prefab&, rename it to &ExplosionPrefab&. Drag the &Explosion& object from &Hierarchy& onto the new &ExplosionPrefab&. Right-click &Explosion& in &Hierarchy& and choose &Delete&.
Right-click &Project& panel and choose &Sync MonoDevelop Project& to open MonoDevelop. Load in the editor BombClass.cs and add this code:
//right under definition of "ySpeed"
public GameObject explosionP
//inside OnTriggerEnter, right after Destroy(this.gameObject)
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
Now switch back to Unity and select &BombPrefab& in &Project& panel & in the &Inspector& you see the new property &ExplosionPrefab&. Just drag &ExplosionPrefab& from &Project& onto this new property field and you&re set to go.
That&s it & press play and see the explosions when you hit sharks. Sweet!
Adding earCandy to the Game
Don&t tell Steve, but iCandy wasn&t enough for us & we need some earCandy too!
How could we have a game be without background music?! We&re going to visit another great guy & Kevin Macleod, who is a great composer releasing film&game music under CC license. So if you use his stuff don&t forget to attribute.
Open this url:
Once you&re there, download &The Cannery& track somewhere to your disc, and drag &The Cannery.mp3&P onto the folder &Audio& in the &Project& panel.
We would like to have the music loop all the time& but which object should we attach it to?
Well, let&s attach it to the camera! The camera is a game object too, and can have other components attached.
Drag &The Cannery& from &Project& panel onto &Main Camera& in the &Hierarchy& panel. Select &Main Camera& in &Hierarchy& and in the &Inspector& find the Audio Source strip & check the &Loop& checkbox and set Volume to &0.20&P.
It&s as easy as that & run the scene and enjoy the new background music!
Creating a GUI with Unity
Let&s dive into yet another new area & GUI. Unity provides you with some standard labels and buttons, but all in all it&s not the biggest strength of Unity. However we&re going to use a label to sh so first we&ll need to implement the score logic.
Switch to MonoDevelop. Open up PlayerClass.cs and add a new property:
public static int score = 0;
Aha! There&s again something new & &static&. This property will be created when the class is loaded and will persist no matter whether there are instances of the class. Additionally this property is accessible from all other classes & this is why we&re keeping the score count in a static property.
Next add this method which will take care of updating the score (not much sense in it now, but just go with it) & see how the score property is accessed via the class name:
public void updateScoreBy(int deltaScore) {
PlayerClass.score += deltaS
Add one more method to PlayerClass & this one will draw the score count on the screen:
void OnGUI() {
GUIStyle style = new GUIStyle();
style.fontSize = 20;
GUI.Label(new Rect(10,10,100,20), "Score:"+PlayerClass.score, style );
This event handler &OnGUI& is getting called on every frame on the GUI layer. So, you draw everything you need on the GUI in here.
GUIStyle is a class, which mimics a CSS class & so you can use fontSize, marginLeft and such if you are familiar with CSS, otherwise just keep with the font size for now. GUI.Label() is a method taking 3 arguments: a rect for the bounds of the label, the string to draw and the text style. That&s all to it.
The only task left is: update the score when we have hits or misses! Open up BombClass.cs and make the following modifications:
//add a new property
public PlayerC&
//replace the existing OnTriggerMethod with
void OnTriggerEnter(Collider obj) {
if (obj.gameObject.name == "Shark") {
//reset shark
obj.gameObject.transform.rotation = Quaternion.
obj.gameObject.transform.position = new Vector3(20f, -3f, 8f);
player.updateScoreBy(+1);
Destroy(gameObject);
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
if (obj.gameObject.name == "ClownFish") {
//reset fish
obj.gameObject.transform.rotation = Quaternion.
obj.gameObject.transform.position = new Vector3(-20f, -1f, 8f);
player.updateScoreBy(-1);
Destroy(gameObject);
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
It&s pretty similar to what we had before, but we&re having a new property called &player& and when we need to update the score we call player.updateScoreBy().
Also to make the game more interesting if you hit a shark you&ll get a point, if you hit a clownfish (remember? clownfish & gooood, shark & baaahhd) then you will loose a point. Now that&s shaping as a difficult game!
There&s one last thing & to set the player property on the bomb. Now we can&t do it like before because bombs are dynamically created, but fortunately the bombs are created by the player himself, so he can set the player property at creation time.
Let&s do that & open up PlayerClass.cs and just under the line &bombObject.transform.position = this.gameObject.transform.& add this code:
BombClass bomb = (BombClass)bombObject.GetComponent("BombClass");
bomb.player =
There&s something new again! Let&s discuss: bombObject is a GameObject instance (returned by Instantiate), so we call &GetComponent& on it and this way we can access all attached components to the game object & the result we cast to a BombClass & so in the end we got the reference to the C# class attached to the game object. Next we just set the &player& property to this (the PlayerClass instance).
Run the scene and you&ll see the score counter!
Unity Objects and Components
At this point you already have enough practice with Unity to be introduced to Unity&s game object model. Better understand what you are actually doing, right? Let&s make a really short de-tour to have a look at how game objects relate to the components attached to them.
All those strips we see adding up in the &Inspector& panel & these are components that get attached to the game object. An empty game object has just its transform strip & position, rotation, scale. That&s all & everything else are components attached.
If you look at our BombPrefab & you can see many different components:
: provides position, rotation, and scale, as described above.Transform
Mesh Filter: provides the geometry of the visible object.
Mesh Renderer: renders the geometry.
Rigidbody: handles physics.
Audio Source: plays audio.
Script: can programmatically update the object.
These are just few of the possible components you can attach to an object. To even better understand let&s have a look at this diagram:
So, take the point-of-view of the Script component. It should now be a bit clearer why we had to call:
Destroy(this.gameObject);
in order to destroy everything related to the object instance. From the gameObject property we can also access all other components, so we can adjust physics or audio volume, etc .etc.
Adding more scenes
Right now our game is getting good, but there&s no way to win or lose!
So let&s add a &you win& screen when the player makes more than 3 points.
From the menu choose &New Scene&, then again from the menu &Save Scene&, select the folder [your project's directory]/Assets/Scenes and save the scene as &WinScene&.
Select &Main Camera& in &Hierarchy& and set: Position [0, 0, 0], Projection to &Orthographic&, Size to &10&P, Near to &0.5&P and Far to &22&P. From the menu choose &GameObject/Create Other/Directional Light& and in the Inspector: Position [0, 0, 0].
All we want in the scene is to put a plane (like the background in our game level) and put an image on it saying &you win&, so let do as before in Part 1: From the menu &GameObject/Create Other/Plane& and in the Inspector: Position [0, 0, 8], Rotation to [90, 180, 0], Scale to [3, 1, 2].
Next download and save to your disc the image prepared by Vicki Wenderlich (click for full resolution):
Drag &gameover_youwin.png& onto &Project& panel in &Textures& folder. After the texture is imported it looks kind of dirty & it&s because of the compression, just select &gameover_youwin& texture in &Project& and then in the &Inspector& find &Format& change it to &16bits& and click &Apply&. Now drag &gameover_youwin& from &Project& panel onto &Plane& in &Hierarchy&. In your &Game& panel you should see the &You win& & where Vicki painted the evil shark floating bely up.
We just need to make it alive & when the scene is tapped the game should restart: Right-click &Project& panel in &Class& folder, choose &Create/C Sharp Script& and rename it to &GameOverClass&. Right-click and choose &Sync MonoDevelop Project&. In MonoDevelop open up the new GameOverClass.cs and replace the contents with this code:
using UnityE
using System.C
public class GameOverClass : MonoBehaviour {
// Update is called once per frame
void Update () {
if (Input.anyKeyDown) {
PlayerClass.score = 0;
Application.LoadLevel("LevelScene");
When the player taps the screen, the score is reset and gameplay scene is loaded. Application.LoadLevel() just takes the name of the scene to load & pretty easy :)
Back to Unity: drag &GameOverClass& script from &Project& panel &Class& folder onto the &Main Camera&.
Now to include this scene in the project choose &File/Build Settings& and in the popup window click &Add current& button and close the window. You&ve added the scene to the project build.
Let&s quickly add the &You loose& screen too! Like last time, make a &New scene&, then &Save Scene& as &LooseScene& in the Scenes folder.
Select &Main Camera& in &Hierarchy& and set: Position [0, 0, 0], Projection to &Orthographic&, Size to &10&P, Near to &0.5&P and Far to &22&P. From the menu &GameObject/Create Other/Directional Light& and in the Inspector: Position [0, 0, 0]. From the menu &GameObject/Create Other/Plane& and in the Inspector: Position [0, 0, 8], Rotation to [90, 180, 0], Scale to [3, 1, 2].
Download this &You Lose& image and save to your disc (click for full resolution):
To wrap up this scene, take the following steps just like last time:
Drag &gameover_youlose.png& onto &Project& panel in &Textures& folder.
Select &gameover_youlose& texture in &Project& and then in the &Inspector& find &Format& change it to &16bits& and click &Apply&.
Drag &gameover_youlose& from &Project& panel onto &Plane& in &Hierarchy&.
Drag &GameOverClass& from &Project& panel &Class& folder onto the &Main Camera&.
From the main menu choose &File/Build Settings& and in the popup window click &Add current& button and close the window.
There & you have 3 scenes, but you need to connect them!
Load the LevelScene scene & by double clicking &LevelScene& in the &Project& panel. Switch to MonoDevelop and open up PlayerClass.cs. We&re going to modify the updateScoreBy method to check whether you made more than 3 points or sank under -3 points.
//replace the updateScoreBy method with this code
public void updateScoreBy(int deltaScore) {
PlayerClass.score += deltaS
if (PlayerClass.score&3) {
Application.LoadLevel("WinScene");
} else if (PlayerClass.score&-3) {
Application.LoadLevel("LooseScene");
Now your scene workflow is set. You can give the game a try by hitting Play in Unity. Actually & why don&t you hit &File/Build&Run&, and when Xcode pops up & hit &Run& there as well and give the game a try on your iPhone?
Going 2.5D & at last!
Yes & it&s time. The epic technique you&ve been expecting for 2 long parts of this tutorial series & 2.5D!
And I&ll tell you in advance a secret & we&re going to spice it up and make it almost 3D for your developing pleasure!
Up to now we&ve been setting the cameras& projection to &Orthographic&, which made the scene look like a plain 2D game & well, that ends here!
In your LevelScene scene select &Main Camera& and in the Inspector change Projection to &Perspective& and &Field of View& to &100&P (to compensate for the perspective). That&s it & hit the Play button and see your game in 2.5D! Ain&t that cool?
But we&re not going to stop here.
Here&s the plan & to make the game more difficult and demonstrate how to rotate and move the camera, every time the score increases we&ll move the camera onto an arc path and change it&s angle. This way, the more you progress in the game the weirder the angle you&ll have to look at the characters and try to bomb the sharks!
Switch to MonoDevelop and make the following changes to PlayerClass.cs:
//add the properties
public GameObject mainC
public GameObject gameB
public float nextZ = 0;&
//at the end of the updateScoreBy method
if (PlayerClass.score&0) {
nextZ = PlayerClass.score*2.5f;
//at the end of the Update method
if (nextZ & mainCamera.transform.position.z) {
mainCamera.gameObject.transform.Translate(
3* Mathf.Sin(transform.position.z/2 ) * Time.deltaTime,
-Mathf.Sin(transform.position.z /2 ) * Time.deltaTime *0.3f
mainCamera.gameObject.transform.RotateAroundLocal( Vector3.up, Time.deltaTime*0.1f );
gameBackground.gameObject.transform.RotateAroundLocal( Vector3.up, Time.deltaTime*0.1f );
Alright & lot of code, but that&s about everything we need. Let&s go over it bit by bit.
First, we declare properties to hold references to the Main Camera and the Background plane. We&ll be moving and rotating the camera, and we will be rotating the background as well.
The Camera is moving from it&s current Z position at 0 towards the background to about 7.5Z. So every time the player makes a score, the nextZ is set to 2.5, then 5.0, then 7.5 & and from these values the Main Camera is translated onto something like an arc using a sin function.
All math functions by the way are accessible via the Mathf class & as for the sin is Mathf.Sin(). Also we rotate the camera using transform.RotateAroundLocal and we pass it an axis to rotate around (Vector3.up) and the angle to rotate by. We rotate the camera and the background together, so camera faces always the background (i.e. the background doesn&t run out of the screen).
One more thing & let&s connect the new public properties. Switch to Unity and select &Player& object in &Hierarchy& panel. Drag &Main Camera& from &Hierarchy& onto the new &Main Camera& property in the &Inspector&; drag the &Background& object from &Hierarchy& onto the new &Game Background& property in the &Inspector&.
Congrats, you&re finally done! Hit File\Build and Run and run the finished game on your iPhone, and enjoy bombing sharks at weird angles :)
Debugging with Unity
I&d like to shortly touch on few topics, because when you go on developing by yourselves you are going to run into trouble where you need to debug your game. So few simple things to keep in mind:
Don&t forget there&s a Pause button in the toolbar, so if you need to stop the execution of the game and check all object&s properties & just hit Pause and then browse around your scene and lookup the values in the &Inspector& panel.
If you&re not sure whether your method fires up, print a message in the console (much like in Xcode). Use: Debug.Log(&message&); to print messages to the Console. You can bring up the Console window by choosing from the menu &Window/Console&.
Develop this habit: When you&re done coding in MonoDevelop and you switch back to Unity editor look at Unity&s status bar (at the bottom of the application window) & if you wrote bad code, which won&t validate & you&ll get an error message in red in there, immediately after you bring Unity up.
If your objects don&t move & triple check if your script is attached to your object!
When you run your game you can change values in the Inspector just to try out different values, etc. etc. When you stop the game: NB all values in the inspector are reset to the ones you had before running the game. Thus effectively if you forgot to stop the game and you made changes, they&ll be lost, so be sure to stop the game after your finished testing and then continue developing.
Where To Go From Here?
Here is the complete sample project that we developed in the above tutorial series.
If you want to learn more about Unity you can look around their web- they have great Support section with examples, forum, etc: . Also have a look at the Unity C# Reference.
If you want to practice more, you can extend Shark Bomber further by adding some of the
following features to the app:
Add explosion sounds, game over scene music/effects
Have 2 different explosions and randomly show them
Have different levels
This is a very very simple introduction to Unity & we barely touched on reading iPhone input, but I think you have now a solid understanding how thing in Unity work and that&s more important to get you started!
If you think about it & you already know everything you need to know to also create 3D games! You&ve been translating objects around, rotating them to weird angles, you&ve been moving around the camera and basically nothing stops you from getting wild in the 3 dimensions. Just choose the right models, build some terrain (usually using a plane is a good idea) and you can pretty much do anything you want. So this was also your quick start into making 3D games with Unity!用Unity3D 做 Flappy Bird 游戏 - 简书
用Unity3D 做 Flappy Bird 游戏
效果展示:
创建项目用到的文件夹 例如 images
scripts等,之后将图片素材拖入到images中, 如下图所示:
接着创建鸟扇动翅膀的动画 如下图所示
小鸟挥动翅膀动画的绘制
这样一个 Bird 扇动翅膀的动画就完成了
接下来呢,该为我们的小Bird 加上上下两个顶部, 如下图所示:
topandbuttom.gif
之后我们为上下两个顶部和小鸟加上碰撞检测并给小鸟加上重力,如下图所示:
加上碰撞检测和小鸟的重力
紧接着, 我们需要为小鸟能在按空格键或者鼠标右键的时候,跳一下,为此,在scripts文件夹下创建birds C# script 文件
小鸟的起跳和碰撞检测
下面解释一下代码:首先,C# 的程序入口在unity3d中被封装成了 Start() 和 Update()两个,其中 Start() 是在游戏启动后仅仅执行一次,一般完成一些初始化工作, 而Update()则是在游戏启动后逐帧执行,也即每帧执行一次Update()函数
第6行 定义了小鸟的飞行速度值, 即可以理解成没按一下按键上升多少距离第14行 检测是否触发了键盘的空格键或者是鼠标的右键,其中GetMouseButtonDown()的参数中0为左键,1为中键,2为右键,若触发则接着执行第15行的动作, 即将小鸟的y轴上的速度加上刚才设置的瞬时速度。第19行 的代码用来检测小鸟和上下顶的关系,若两者碰到则在终端打印 "Game Over" 并重新加载游戏ps: 这里要注意将上下两个顶部的名字重命名成为end
之后将上述写好的代码单击按下不要松开拖到bird上,像如下所示:
下一步先将照相机的投影模式改成正交模式, 因为我们做的是2d游戏,所以选择正交模式更加适合一些
22_07_15_09_48_16.png
然后为Flappy Bird 添加背景图片 首先和小鸟图片一样将导入的背景图片变成unity可以直接用的2d精灵图片, 之后直接拖到我们的场景中就可以了如下图所示:
分别调整背景和小鸟的layer
Paste_Image.png
这样一个基本的雏形已经完成了, 下面就该为小鸟添加障碍物
在这之前, 为了界面简洁可以将背景图片和上下顶部放到一个空的GameObject里然后命名这个GameObject为BG, 即如下图所示
22_07_15_09_47_00.png
接着将我们images文件夹中的pipe1像之前那样编程unity可用的精灵对象,之后拖到我们的场景列表中放置好位置后,复制一个相同的pipe出来 然后旋转180并拖动位置 像下图所示:
22_07_15_09_56_01.png
因为这两根柱子必须要对齐才行所以创建一个新的GameObject将两根柱子拖到其中,并命名该GameObject 为pipes
这样我们的柱子的场景就做好了 接下来 我们要做的是让柱子动起来,首先将其移出视线内,然后在scripts文件夹中创建Move c# script 文件用来控制柱子的移动
Paste_Image.png
第6行: 首先设置柱子移动的距离 这个大家需要自己算一下自己的 我的柱子是从右向左 分别x的坐标为(7)和(-12)所以移动的距离为-19第7行: 设置了柱子移动的速度值第8行: 定义了柱子的终止位置(即一个三维向量)第11行: 在Start() 函数中首先计算出endPos坐标第16行: 在Update() 函数中计算柱子实时坐标第17行: 该行用来检测柱子是否移动到了终止坐标,一旦移动到了,则自我销毁。
到了这一步,我们的鸟儿应该可以穿越柱子啦, 但是这时候小鸟碰到柱子上并不会有什么反应,然么怎么加上小鸟碰到柱子时候结束游戏呢? 最简单的办法就是修改两个柱子的名字和上下底部一样为 end 并给柱子加上碰撞检测组件即如下图所示:
Paste_Image.png
接下来我们创建更多的柱子, 为了实现这一点,要用到一个叫做预制的技术首先在images, scripts等在同一目录创建一个新的文件夹叫做 prebab。
然后如下图所示,将场景中的pipes对象拖到prefab文件夹中做成预制件:
prefab.gif
然后在scripts文件夹中创建一个新的名叫 CreatePipes 的C# script 文件先将其拖拽到Main Camera下作为其组件,并写下以下代码:
Paste_Image.png
第5行: 首先创建一个pipesPrefab的GameObject 待会用来关联之前的pipesP第8行: 重复调用 "Create"函数第12行: 实例化pipesPrefab, 即不断的制造柱子
写完后保存回到Unity3D 将prefab文件夹中的pipes和Main Camera中的 pipesPrefab 关联(即拖拽到标签为pipesPrefab 的值中)之后就可以将场景中原来的pipes 删除掉。
完成后效果如下图所示:
prefab2.gif
这样就能源源不断的出现柱子啦! :)
很显然,我们不能让柱子一直这么以一个不动的姿态出现, 下面来看看如何让柱子的高度发生些变化:完成这一步其实非常简单我们只需要自己测量下柱子在屏幕中y轴的上下临界值即可(例如pipes的y轴设置为3则上面的柱子恰好在屏幕上看不到,y轴设置为-3则下面的柱子恰好看不到)
修改CreatePipes这个脚本文件的第12行为:以下代码:
Paste_Image.png
该代码是重载了Instantiate这个函数其中第二个参数就是设置柱子出现的位置,第三个是柱子的旋转角度,这里我们像如上代码设置为恒定值即可。
如此以下 我们的柱子出现的时候位置就是随机的啦,效果如下所示:
prefab3.gif
接下来,我们为小鸟加上分数, 即每通过一个柱子,获得一点分数, 首先在场景中添加一个 Canvas(在场景列表中右键UI中选择Canvas)并在Canvas中添加Text移动到适宜的位置并修改其内容为0
Paste_Image.png
接下来我们要如何知道小鸟通过了一个柱子呢? 这里用到触发检测, 即一种特殊的碰撞检测(不影响物体的运动,仅仅检测两者有没有碰着)
将pipes从prefab中拖回到场景列表之后在pipes中新建一个Cube并用其填充两个柱子之间的空隙,如下图所示:
接着如下图做一些修改:
pipes2.gif
到这里触发体就设置好了,下面通过一个脚本来测试是否通过柱子并为其加分, 打开 之前创建的 Bird C# script 文件
Paste_Image.png
第2行: 添加UnityEngine.UI库 以便可以获得Text对象第7、8行: 分别定义scoreText对象和整型score变量第30行: 该函数用于处理触发离开事件(即小鸟飞过柱子后分数+1)
保存退出后,将Canvas中的Text和bird1对象的组件中的ScoreText关联起来
之后修改场景列表中pipes下Cube名称为score之后点即右侧的Apply然后删掉该pipes
score2.gif
最后一步, 得分时,如何加上声音呢,首先我们创建新的文件夹叫做audio并且将我们的声音资源文件添加进来, 然后打开 Bird 脚本文件 添加以下第6行和第35行代码之后保存退出:
Paste_Image.png
Paste_Image.png
然后将声音文件 关联到bird下得的coin:
最后点击bird添加AudioSource组件,如下图所示:
audioSource2.gif
到目前为止,我们的FlappyBird小游戏就告一段落了。。。
感谢各位看到这里。。。

我要回帖

更多关于 unity3d游戏制作 的文章

 

随机推荐