赛车游戏教程第一章,翻译给自己看的。不喜勿喷。

来源:互联网 发布:Mac下载慢 编辑:程序博客网 时间:2024/05/18 21:38

“The Car Tutorial” Part 1

汽车教程第一部分

Creating a Racing Game

for Unity

unity创建一个赛车游戏

Introduction 3介绍

We will show 3演示

Prerequisites 3前置技能

We will not show 4不会演示的

Part 1: Assembling the Car 5装配汽车

Adding Collision 6添加碰撞

Shadow settings for the car model 7汽车模型的影子设定

Adding the Car’s Components 8添加汽车的组件

Adding a blob shadow 10添加位置阴影

Skidmarks 11滑痕

Max Marks 12最大标记

Mark Width 12标记宽度

Ground Offset 12地面偏移

Min Distance 13最小距离

Texture 13纹理

Adding Sound 14添加声音

Finalizing the Assembling 15完成装配

 

Introduction介绍

The aim of this tutorial is to show you how to create a racing game with Unity. We are going to

assemble a car from a 3d model, scripts and Components. We provide you with a complete project

of a driving game, where you can play with a fi nished scene and explore how everything is put together.

此教程目的在于演示怎样用unity创建一个赛车游戏。我们将从一个3D模型中装配一辆车的脚本以及组件。我们提供了一个赛车游戏的完整工程,你可以玩玩,观察这些东西是怎样调整到一起的。

We also provide you with a scene that has everything ready but the car, which you will then

work on completing.

我们同样给你提供了一个没有汽车的赛车场景,用来让你完成它。

We will show演示

Let us begin by talking about what this tutorial will deal with. It is divided into three distinct sections

that can worked on independently of each other:

首先,让我们谈谈这个教程将会怎么组织。它被分成了3个不同的章节。

它们互相之间比较独立。

1. Assembling the Car装配汽车

How to assemble a Car Prefab from a 3D model, scripts and components. This is the section you are

reading right now.

讲述怎样从一个3D模型中装配一辆汽车,添加脚本和组件。这个章节是你现在要读的

2. Tweaking the Car微调

How to tweak the car to behave “better” or in different ways.

各种不同的方法用来把汽车微调得“更好”

3. Under the Hood原理

A more in-depth look at the actual code that drives the car.

更深层次地分析实际的代码。

Prerequisites前置技能

The tutorial is not intended as an entry point to learning Unity. You should have a basic understanding

of how Unity is organized, what a GameObject is, what Components are and so on. Some

proficiency in scripting is also recommended. This being said, we will explain a lot of stuff along

the way, basic and advanced.

此教程不打算当做unity入门教程。你应该对unity有一个基础的理解。比如unity是怎么组织的、什么是gameObject以及什么是Components等等。精通代码也是必要的。也就是说这里很多知识点,高级低级都有。

We will not show不会演示的

• All the other scripts.所有其他的脚本

• The very basics. We will not go in depth with explaining the basic workflow and components in

Unity. For that there are many other resources available at: 非常基础的东西。我们不会深入地解释基本工作流程以及组件的运作。这些东西参考如下教程

http://unity3d.com/support/documentation/video/

http://unity3d.com/support/resources/

The User Manual and the Scripting Reference are valuable companions as you follow along this

tutorial. We suggest that you visit these resources when ever you encounter a built in Component

or function that you’d like to know more about.

阅读本教程时,使用用户手册以及脚本参考是一个好的选择。我们建议你碰到了想要更多了解的内置的组件或者内置函数就去查阅这些资料。

The approach taken at first is that of code monkey see, code monkey do: You follow the instructions

we give about putting a car together and changing it’s variables. Hopefully you will be curious

about how it works, learn something from seeing how everything is put together and do some

investigation on your own. Feel free to explore.

这个方法一看就会:你按照我们说的装配好汽车,然后调整它的值。你将会好奇这个东西是怎样运行的,学学这些东西是怎样被装配到一起,然后做自己的一些调查,随意探索。

In the last and longest section we dive more deeply into the actual code that makes the car drive.最后一个也是最长的一个章节,我们将更深入地进入让汽车运行的真正的代码。

This is not a line-by-line walkthrough, but we will cover most of what is going on. One way to learn programming or improve ones skills is to look at a lot of code (supplemented by doing a lot of

programming). We are certain that you will learn a lot from following this closely and getting an

understanding of how the code works together.

这不是一个逐行运行的流程,但是我们封装了大部分。一个学习编程或者提高技能的方法就是阅读大量代码(辅之以大量编程)。我们确信你将会在观察代码怎样组织中获益匪浅。

 

 

Part 1: Assembling the Car装配

Download the zipped project folder from http://unity3d.com/support/resources/fi les/CarTutorial.zip

http://unity3d.com/support/resources/fi les/CarTutorial.zip下载已经打包的工程。

Start by opening the scene named ‘CompleteScene’. This scene has the car already setup, so you

can try it out by pressing the Play button. This will show you the end result of what we are going

to build.首先打开名为“CompleteScene”的场景。它演示了你要做到的最终效果。

When you are done playing around, open the scene named

TheTrack’. This scene contains what is needed to race, except the

most important part - a car.

当你玩完一圈之后,打开TheTrack场景。这个场景中包括除了车的赛车游戏场景中的一切。

Now drag the car model into the Scene. In the Project view you find it under Models/Car/catamount.

Depending on where you dragged the car, you probably want to change it’s position to a more

suitable one. I suggest that you change its position in the inspector to something like (860, 102.3,878) and set it’s y-rotation to 130.

现在拖动汽车模型到Scene面板中。它Project视图中的Models/Car/catamount.

我建议你将汽车的位置调整为(860, 102.3,878)设置y-rotation130

For the rest of the tutorial, this GameObject will be referred to as ‘Car’ so you might as well

rename it now.

这个gameobject将会在后面的教程中称为汽车,所以你最好将它也重命名为“car

This is just the 3D model of the car. If you look in the Inspector, you will see that it contains a number

of children such as the car’s body, windows and wheels. It also contains two simple meshes that

we will use for the car’s colliders. Don’t worry about them being

visible for now, we will change that. Take some time looking

at how the car is arranged by different parts, and how they are

related to each other in the hierarchy.

这只是汽车的3D模型。你在监视器面板中将会发现它包含了几个子项目,像车的身体,窗户以及轮子。它也包含了两个简单的mesh,我们将它们用作汽车的碰撞器。不要担心他们现在是可见的,我们将会修正它。花点时间看看汽车的不同部位是怎样组织的,以及在hierarchy面板中是怎样的关系。

For various reasons, we want the car to be in it’s own layer. With

the Car GameObject selected, go to the Inspector and select ‘car’

in the layers drop down menu. In the popup menu click ‘Yes, change children’ to make the change

apply to all GameObjects in the car’s hierarchy.

我们有足够的理由让汽车有自己的层。当汽车gameobject被选中时,去监视器面板中的layers下拉框中选中car。在弹出框中选则Yes, change children这样将修改应用到所有子项当中。

The Car GameObject has an Animation component attached by default. Since this is not something

we are going to use, go ahead and do a little clean up by clicking the small wheel to the right of

the Animation Component and selecting ‘Remove Component’.

汽车的gameobject有一个缺省的动画组件。因为没有我们将要用到的东西,所以点击Animation Component旁边的小齿轮选择‘Remove Component’清理掉它。

Adding Collision添加碰撞

Now we’ll set up the collision components for the car to

prevent it from falling through the ground when running

the scene. Instead of using complex mesh colliders based

on the actual mesh of the car, we have setup two meshes

that are much simpler, that fi t the top and bottom of the

car. For performance reasons, we are using these meshes

as the collision model.

现在我们将为汽车设置碰撞组件来让它不能穿过地面。我们设置两个简单的mesh来代替实际上的汽车mesh,一个表示顶部一个表示底部。由于性能上的原因,我们将使用它们来作为碰撞模型。

• Click on the Collider_Bottom game object which is located as a child of the Car.

点击car下面的子项,Collider_Bottom

• Go to the Component/Physics Menu and click the MeshCollider to add one to the game object.

选择菜单中的Component/Physics/ MeshCollider来增加碰撞器

• Click the Material dropdown-selector on the newly added MeshCollider component and select the Car physics material.

选中新加入的MeshCollider组件选择Material下拉框中的Car physics material.

• Check the two boxes ‘Smooth Sphere Collisions’ and ‘Convex

选择Smooth Sphere Collisions’ and ‘Convex

• Since the colliders are going to be invisible, go ahead and remove the MeshRenderer and Mesh Filter Components from the GameObject (Click the small cog wheel to the right of the Components and select ‘Remove Component’.

删掉meshrenderMesh Filter让碰撞器不可见(点击右上角的小齿轮选择‘Remove Component’

 

• Do the same as above for the Collider_Top game object.

Collider_Top做同样的操作

Shadow settings for the car model汽车模型的影子设定

We are going to change the shadow settings for the car model for two reasons. First of all turning off shadow casting or receiving for objects that don’t really need it is very good practice for performance reasons. Second of all we feel that it looks better to not have the car receive shadows. It might be more pleasing to the eye that shadows are not constantly appearing and disappearing on the car when it is traveling at high velocity under the level geometry. It’s up to you what you prefer though. If you want more realistic shadow behavior, it is entirely possible. Just change the settings

according to your liking.

我们有两个理由改变汽车模型的影子设定。第一个,性能上面接受影子的投射不是一个很好的做法。第二个,汽车上面没有影子看起来更舒服。当汽车速度很快时,眼睛可能对汽车上闪过的阴影不舒服。其实这个由你自己,如果你想得到更真实的效果,完全可行,你只需要改变相关设定就行。

The settings we use for the various parts of the car are the following:

用到的一些设定:

Body: Cast Shadows enabled. Receive Shadows disabled.

 

Body Interior: Cast Shadows enabled. Receive Shadows disabled.

Car Windows: Cast and Receive Shadows disabled

8

DiscBrakes: Cast and Receive Shadows disabled

Wheels: Cast Shadows enabled. Receive shadows disabled.

Adding the Car’s Components添加汽车组件

Now let’s start adding the components needed to make the car actually work onto the Car GameObject.

现在,让我们开始添加让汽车真正运作的组件。

First of all, we need a way to control the car’s position in the world by physical simulation, and the built-in RigidBody component is perfect for that. With the Car Game Object selected,go to the Components menu and select Physics/RigidBody. Accept the message Unity gives you about losing prefab connection, and observe how the GameObject now has a Rigidbody attached as one of it’s components.

首先,我们需要一种物理仿真的控制汽车位置的方法,RigidBody是个完美方案。选中car gameobject 在菜单中选择Components / Physics/RigidBody。在提示中点击确定,然后观察rigibody是怎样的一个组件。

• The car obviously weighs more than just one kilo, so start by changing the Rigidbody’s mass to something more realistic like 1500.

汽车明显地比1千克重,所以修改mass1500

• Next we have the drag and angularDrag properties, which are forces that slow down the Rigidbody’s speed and rotation. We will control the drag of the car through scripting, so just set the drag and angularDrag properties to 0.

下一步修改drag and angularDrag属性列,它们使得rigidbody的速度和转动变缓。我们将通过脚本来控制它,所以将它们设置为0就行了。

• Locate the Car.js script in the folder ‘scripts/JavaScripts’ and drag it onto the Car GameObject.

scripts/JavaScripts找到Car.js将它拖动到car gameobject

This script is the “engine” of the car, and is the script we will focus on explaining the most at the end of this tutorial.

这个脚本是汽车的“引擎”教程最后我们将解释大部分的脚本。

The Car-script component has a lot of different variables that will be explained when we start tweaking the car, and even more when we walk through the code. For now we just want to setup what is needed to be able to take the car for a quick test run.

First of all, the car script needs to know about the wheels that the car has. In the Inspector you will see the Front Wheels and the Rear Wheels, and notice that both of them can be expanded by clicking on the small arrow to the left of the names.

汽车脚本有一大堆的变量,我们将用它来微调。现在我们仅仅需要让它赶快运行起来。首先,汽车脚本需要知道汽车的轮子,在监视器中你将看见前轮和后轮,注意它们俩都可以展开。

• Set the size of the Front and Rear Wheels to 2, making room for two front wheels and two rear wheels.

设置size2,给每两个轮子腾出空间

• Now expand the WheelFL, WheelFR, WheelRL and WheelRR in the inspector. You will see that they each have a DiscBrake as a child, and that each disc brake has a wheel as a child. For now you should be content with knowing that the discbrake and wheel game objects are the graphical representation of the wheel.

现在在监视器中展开WheelFL, WheelFR, WheelRL and WheelRR。你将会看见它们都有一个刹车,每一个刹车都有一个子轮子。现在你仅仅需要知道刹车和子轮子是轮子的图形表示就够了。

• Drag the DiscBrakeFL and DiscBrakeFR to the two open slots in the Front Wheels under the Car script and the DiscBrakeRL and DiscBrakeRR to the slots under the Rear Wheels.

拖动DiscBrakeFL and DiscBrakeFR到汽车脚本中前轮的槽中,DiscBrakeRL and DiscBrakeRR到脚本中后轮的槽中。

• You might ask - why are the DiscBrakes the wheels? And the explanation is simple: The disc brakes are parent Game Objects to the tire graphics, so setting the discs as wheels will include the tires.

你可能会问,为什么把刹车放到这个位置?答案很简单:图形上刹车是轮胎的父节点,设置刹车同样改变了轮胎。

10

Adding a blob shadow添加位置阴影

The directional light will make the car cast a nice shadow on the road if shadows are enabled in your project. But we also want to add the shadow that is under the car, as seen in the image here.

如果在你的项目里影子是允许的,方向光将会使汽车投射出一个很好的影子到道路上面。但是我们也需要汽车底部的影子,来当做汽车位标。

For that we will use a projector that projects a blob shadow resembling the shape of the car onto the road directly under the car.

我们将使用一个投射器,用来投射一个近似于汽车形状的位置阴影到汽车底部的地面上。

A projector is a built-in component that works just like a real life projector. You specify the texture that you want it to transmit, and based on the settings for the projector and the distance to the target(s), it will draw this texture onto the objects that are in it’s way.

一个投射器是像真正的探照灯一样的一个内置组件。你指定它发送的纹理,以及与目标的距离。那么它将把这个纹理按照它的方式画到该画的地方。

• In the Hierarchy, create an empty GameObject and drag it to the Car to make it a child of it.

hierarchy中,新建一个空的gameobject,然后拖动它到汽车上,使得它成为汽车的一个子项。

• Name it Blob shadow projector

更名为Blob shadow projector

• Add a Projector component to the Blob shadow projector (Component->Renderer->Projector)

向其中添加一个投射器

• Set the projectors Near Clip Plane to 0.1, its Far Clip Plane to 50, its Field of View to 30.

设置投射器近裁剪面Near Clip Plane0.1 远裁剪面Far Clip Plane50,它的视口Field of View30

• Assign the Blob_shadow material to its Material slot.

将材质选择为Blob_shadow

• In the ‘Ignore Layers’ select ‘Everything’ and then deselect the ‘Road’ layer, thus making the projector only cast the blob shadow on the road.

Ignore Layers中选择Everything取消road的选定。这样使得投射器只将影子投射到道路上。

• Add the BlobShadowController.js script (in the Scripts/CSharpScripts folder in the Project view)The position and rotation of the Projector Component gets updated each frame in the Blob Shadow Controller script, which is pretty simple. In short, it is placed 10 meters above the car and gets it rotation set based on the rotation of the car. You can take a look at the script and try changing the values if you want the car’s blob shadow on the road to look differently.

添加BlobShadowController.js到投射器组件上。它将设置投射器每帧的位置和朝向。

这个控制脚本相当简单。它将投射器放到汽车上面10米的高度,设置它的朝向为汽车。你可以试着修改里面的值来让它看起来不同一些。

Skidmarks滑痕

Some of the things that make it fun to drive the car are pushing the car to slide around a corner or doing a u-turn at high speed. To enhance the effect of the wheels sliding on the road and make it a bit more believable, we are going to add some skidmarks to the surface we’re driving on when the car is sliding.

开车的乐趣往往来自于汽车滑过一个弯道或者做一个高速u型转弯。提升轮胎在路上的滑动效果使得它更使人信服,当汽车滑动的时我们添加一些滑痕表面。

The way we set the skidmarks is by having a script that controls all the skidmarks in the scene. This controller is responsible for creating the mesh that represents the skidmarks. Each wheel knows its own position, and whether or not it is sliding. We use this information to register a point in the world where we want the skidmark to be in relation to the skidmark controller. We let each wheel keep track of the previous skidmark-point so that the skidmarks from several wheels don’t get mixed up.

我们通过一个脚本来放置场景中所有的滑痕。这个脚本负责创建滑痕的mesh。每个轮胎知道它自己的位置,以及是不是滑动的。当我们想使用滑痕控制器的时候使用这些信息来注册一个点。

我们让每一个轮子记录先前的记录点,让每一条滑痕不会弄混。

We have created a prefab for this that you can just drag into the scene:

我们已经创建了一个prefab来做这些,你仅仅需要将它拖动到场景中。

• Drag the Skidmarks prefab from Prefabs->VFX->Skidmarks into the scene.

Prefabs->VFX->Skidmarks拖动Skidmarks预置体到场景中

“The Car Tutorial”― Creating a Racing Game for Unity, Part 1 unity

12

We set the intensity of the skidmarks by adjusting the color of each vertex created. The intensity is determined by how much the wheel is skidding. For this to take effect we use a customized shader that uses the alpha from each vertex when rendering the skidmarks.

我们通过调整颜色来表示滑痕的强度。强度由轮胎滑动了多少来决定。这个我们使用一个自定义的shader,里面使用了alpha

As with the car there are several things that can be changed to make the skidmarks match better to the car that you are trying to build. Looking at the Skidmarks Component on the Skidmarks gameobject you should see that there are a few public variables that can be tweaked.

对于汽车来说,这里有一些能够使得滑痕更好的地方。skidmarks 组件中你应该能看到这里有一些能够修改的公有变量。

Max Marks最大滑痕数

The Max Marks variable determines the number of positions for the skidmarks that can exist in the scene at any time. All the wheels are using the same Skidmarks, so this number counts for all wheels.

最大滑痕数变量决定了场景中同一时间内能够存在的最大数目的滑痕。每一个轮子都使用相同的滑痕计数。

Whenever the maximum number is reached, the ones created first will be overwritten.

Increasing this number will also increase the combined length of all the pieces of skidmarks in the scene.

无论何时到达了最大数量,第一条将会被覆写。增大这个数字也将提升场景中滑痕总长度。

Mark Width滑痕宽度

The Mark Width sets the width of the skidmarks. This has to be adjusted to fi t the wheels of the vehicle created. If it is a monster truck you are trying to make a very wide skidmark might be needed, and if it is a supersonic car with ultra-thin tires made for setting the ground speed record, a very thin skidmark could work better.

滑痕宽度必须调整得和车辆的轮子一致。如果是一辆怪兽卡车,它的滑痕必须很宽,如果是一辆极小轮子的超音速汽车,就需要一条非常细的滑痕。

Ground Offset

When the mesh for the skidmarks is created, it will be created using the points calculated from the wheels for positioning the skidmark patches. These points will most often be right on the surface of whatever the wheel was driving on at the time it was sliding. When two meshes are rendered right on-top of each other, it might give some flickering results in the game.

滑痕的mesh将用从轮子的地点计算出来的点来创建。这些点常常是刚好的或者每当轮子滑动时就出现,当两个meshes重叠的时候,可能会出现闪烁的情况。

To prevent this the Ground Offset variable is introduced. The mesh created will be raised by the length of the offset in the direction of the normal of the surface that it is created over. So if some flickering occurs, or the skidmarks intersect with the surface, try increasing the offset.

位移变量就是解决这种情况的。只有比这个值长的滑痕才会被创建。如果又出现了闪烁,或者滑痕与表面相交,试着提升offset的值。

To further ensure that the skidmarks are rendered on top of the ground, the shader used for the skidmarks has been given an offset, and has been assigned to another render queue than the standard one.

为了进一步保证滑痕是在道路表面,滑痕的shader已经提供了一个offset值,它已经被付给另一个渲染队列。

Min Distance最小距离

When a new point is added to the SkidmarkController it has to be Min Distance away from the last skidmark point added by the same wheel. That ensures that you don’t waste points on adding skidmarks on a very small area. Don’t set this value too high though, since that might make the patches of the skidmarks too long, and furthermore an increased distance might appear as lag, i.e. the skidmarks appear behind the wheels. Decreasing the value will, to some extent, smooth the skidmarks, and make the skidmarks be created closer to the wheels.

当添加一个新的点到滑痕控制器时,它与同一轮子最近的滑点必须得比最小距离大。确保你不会浪费点在一个很小的范围,不要将这个值设置得太大,不然会让滑痕出现得太晚。调整这个值,让它能够与轮子配合得很好。

 

Texture纹理

The tire pattern for the tires on a monster truck are quite different compared to the tire patterns on wheels from a formula one racer. The texture used for the skidmarks resembles the marks the given tire pattern of the wheels will make on the surface. If you created another type of car, with very different wheels, you would need to change this texture if you want the skidmarks to match the wheel.

怪兽卡车的轮胎图案与一级方程式赛车的轮胎图案有很大不同。滑痕的纹理类似于将轮胎的图案画在表面上。如果你创建了另一种轮子很不相同的汽车,你必须得改变滑痕的纹理来与轮子一致。

14

Adding Sound添加声音

• Add the SoundController.js script to the Car game Object. (Drag it from cripts/JavaScripts/Sound-Controller.js).

添加SoundController.js脚本到汽车gameobject

The Sound Controller component has several slots for audio, that we need to assign the different audio fi les to. The audio fi les are in the Sound/Car folder in the Project view. Drag the:

声音控制组件有几个槽,我们需要用不同的声音文件赋给它。声音文件在工程面板Sound/Car文件夹中。

CarEngine_D_upper-register to the D slot.

Set the Volume to 0.565

CarEngine_E_midlow-register to the E

slot. Set the Volume to 0.8

CarEngine_F_midhigh-register to the F

slot. Set the Volume to 0.78

CarEngine_K_passing-rush to the K slot.

Set the Volume to 0.565

CarEngine_L_lower-register to the L slot. Set the Volume to 0.71

Wind-loop_stereo_22khz_16bit to the Wind slot. Set the to Volume 0.8

CarEngine_DEFL_tunnel-add_small to the Tunnel Sound slot. Set the Volume to 0.8

Collision1 to the Crash Low Speed Sound slot. Set the Volume to 0.8

Car_crash1_smaller to the Crash High Speed Sound slot. Set the Volume to 0.5

Car_skid1 to the Skid Sound slot

CarTutorialSong to the Background Music slot. Set the Volume to 1.

15

The volume settings are of course just suggested values. You can play around with different values to get the exact sound image that you prefer. Or you could take it even further and build your own settings menu for sound, allowing to tweak volume for music and effects separately in-game.

这些数据仅仅是一个建议。你可以使用你自己喜欢的值。甚至你可以建立你自己的音乐菜单,在游戏里可以调节音量。

Finalizing the Assembling完成装配

Finally drag the following scripts onto the Car game object:

最后拖动以下脚本到汽车gameobject

LightmapperObjectUV.js (from scripts/JavaScripts)

CrashController.js from (scripts/JavaScripts)

Generate2DRefl ection.cs (from Scripts/CSharpScripts)

We need to do one final thing before we can try out the stuff we just created. The camera needs to know what to look at and follow, otherwise we’ll just drive the car out of the view as soon as we start moving.

我们需要做的最后一件事就是让摄像机知道怎么跟随拍摄,不然我们会很快离开视线。

• Go to the Main_Camera Game Object and set its Target (under the Car Camera script component)to the Car Game Object.

Main_CameraTarget设置为汽车gameobject