字幕表 動画を再生する
In Unity 4.3 we're launching our first set of 2D features.
Unity 4.3 より新たな2D機能が追加されました。
To compliment this we have constructed a
我々の作成したデモを元に、
demo project with these tools.
これらの機能を解説したいと思います。
Our 2D platformer is nicknamed 'Tower Bridge Defence'
この「Tower Bridge Defence」というゲームは
It depicts London's Tower Bridge in the midst
宇宙人の侵略に晒されている
of an alien invasion.
ロンドンのタワーブリッジを描いたデモです。
It's a completely sprite-based, physics driven
これは、スプライトのみで構成された物理駆動のゲームで、
2D sample level that we hope will help you
Unityにおける2Dゲーム制作の理解に役立つのではないかと思います。
understand how 2D games are put together in Unity.
この動画では
This video will discuss the background and
デモの背景と前景の作り方
foreground construction, characters, effects,
キャラクター、エフェクト、カメラの追従
camera tracking, animation and scripting
アニメーションとスクリプトについて解説します。
used in the demo.
まずは、Unity 2Dの基本的な操作を説明しましょう。
To begin with, let's discuss the basics
まず、2D機能を使うにあたって
of working in 2D in Unity.
「Editor Behaviour Mode」を2Dにしてください。
Firstly, when working in 2D, you should set the
新規プロジェクトウィザードのドロップダウン
Editor Behaviour Mode to 2D
またはメニューから Edit > Project Settings > Editor
for various settings.
で設定出来ます。
This can be done when making a new project
この設定により
using the drop-down on the project wizard
インポートされたテクスチャーはデフォルトでスプライトに設定され、
or during a project by choosing
「Scene View」のデフォルトの表示は2Dになります。
Edit - Project Settings - Editor from the top menu.
このモードでは2Dゲーム制作を行いやすい様に
This means that by default textures
ビューは並行投影になります。
will be imported as sprites and the
そして、ビューの右上に表示されている3D Gizmoが非表示になり、
Scene View will default to 2D mode.
より広いスペースを使えるようになります。
This new mode gives you a completely orthographic
この設定以外の点では
view in which to construct 2D games.
2Dのワークフローは従来の3Dゲームを作るアプローチとよく似ています。
It also hides the usual 3D gizmo
なので、既にUnityを使ったことがある方なら
in the top right of the view, giving you more space
すぐに2Dゲームを作ることができると言うことです。
to work in. Aside from these settings the work
また、2Dと3Dの要素は混在できるので
flows for 2D have been designed to mirror
2Dゲームに3Dの要素を加える事も
existing Unity approaches to 3D game creation.
またその逆に3Dのゲームに2Dの要素を加えることもできます。
So if you already know a little about Unity
ではデモプロジェクトを元に
you'll be in a great position to start making
我々がどのようにステージを作成したのかを見てみましょう。
2D games right away.
まず、Photoshopでステージ構成の概要を作成し
It's worth noting at this stage that you can
そこからレイアウトを決めました。
still mix 2D and 3D in Unity,
レイヤー毎に書き出す事で、
so if you want to add 3D elements to your 2D game
Unityのスプライトタイプとしてインポートできます
or vice versa you can do that with no worries.
背景を視点に応じて移動させるため
Let's take a look at the demo project itself,
いくつかの背景要素は別にして
and how we built it up one stage at a time.
Background Sorting レイヤーに配置します。
We began by sketching out the level design
これはUnityの新たなもう一つの2D開発機能です。
for this sample level and then went about
このレイヤーにすべての背景を追加する事で、
recreating the layout in Photoshop.
Order In LayerというSprite Rendererのプロパティで
Creating and exporting the layers,
一括して描画順番を変更する事ができます。
we were able to import these in to Unity
配置位置が決まったなら
using the new Sprite type.
Sorting Layerの”Background”をロックする事で
In order to create parallaxing in our background later,
前景の要素を追加するときに
we kept some of the background elements separate
間違えて背景を動かせることを予防できます。
and placed them on to a Background Sorting Layer.
右上のLayersドロップダウンで
Yet another new feature of 2D development in Unity.
この設定を指定できます。
Having assigned all of our backgrounds to this layer,
背景は飾りの要素だけですので、
we could then use the Order In Layer property
スプライト以外のコンポーネントは必要ありません。
of the Sprite Renderer to sort them.
背景オブジェクトの親オブジェクトには
Once we were happy with their positions
視点に応じて位置を操作する
we could lock the Background Sorting Layer
BackgroundParallaxという単純なスクリプトが追加してあります。
so that when we added foreground elements
このスクリプトに関しての詳しい説明は
we didn't need to worry about accidentally
Scriptsフォルダにあるスクリプトのコメントを参照して下さい。
dragging background elements around.
次は、前景の要素、キャラクターの作成です。
This is done using the Layers pull-down in the
デザインはロンドンのタワーブリッジの中に
top right of the interface.
UFOが着陸した状況です。
Because the background elements are purely decorative
プレイヤーはフィールド内を動き回り、
we did not require any additional components
敵は空から登場して
on the sprite game object.
フィールドの中を移動します。
They were parented to an empty game object
そういった、キャラクターの移動のために、
that has a simple script to handle parallaxing
各前景の部分にはコライダーが必要です。
called BackgroundParallax.
大体のフィールドには2DのBox Colliderで良いのですが、
For more information you'll find this script
UFOの形はかなり複雑です。
fully commented in the Scripts folder.
UnityのPolygon Colliderはスプライトの形に基づき
Next up came the creation of the foreground elements
自動的にコライダーを作成してくれます。
that our characters would actually traverse.
また、生成されたコライダーの形を手動で調整する事も可能です。
We designed London's Tower Bridge with a UFO
ポイントの移動、追加、削除で
landed in the centre.
コライダーの形を歩かせるのに適切な形にします。
The character has the run of the environment
前景を背景より手前に表示するために
as enemies spawn from the skies and begin
Tags and Layersマネジャーに
to navigate around the level.
"Foregrounds"ソートレイヤーを作成してあります。
As such, each piece of the foreground required
次は、プレイヤーキャラクターを見てみましょう。
a collider for characters to walk upon.
プレイヤーキャラクターもPhotoshopでデザインしました。
For most of the environment we used 2D
2Dゲームに合うように
box colliders for efficiency,
Raymanの様に手足が独立したデザインです。
but the UFO itself has a more complex shape.
もしくは、スプライトアニメを用いた コマアニメーションで表現する事も可能です。
Unity's Polygon Collider allowed us to
そのアプローチは後で背景の鳥に使用します。
automate creation of the collider itself
キャラクターの手足を別々に動かしたいので
based on the shape of the sprite.
Unityが別のスプライトとしてインポートされる様に
It even meant that we could tweak the shape of
それぞれ分割して配置します。
the collider later.
これにより、全てのスプライトを独立的に動く様に配置する事ができます。
Moving, adding or subtracting points
新しい"Character"ソートレイヤーに配置して
of the collider shape to make it more
PositionのZの値を入力して描画順を設定します。
appropriate to walk over.
プレイヤーキャラクターのスプライトは空のGameObjectの子供に設定し
To sort these foregrounds we created a
親のオブジェクトにはコントロールスクリプト、コライダー、
Foregrounds Sorting Layer, which was drawn
フィジックス、その他を付加します。
above the backgrounds in the Tags And Layers manager.
その後、新しくなったAnimation Windowで
Next, let's take a look at our hero.
待機、移動、ジャンプ、攻撃、死亡の時の
Our player character was yet again designed
各スプライトのパーツの動きを設定します。
in Photoshop, and for this demo
Animation windowのDopesheetビューを使う事で
we chose to make a character with independent
簡単に設定ができます。
limbs and features in the style of
親オブジェクトにアニメーションを追加して
2D hits such as Rayman.
子オブジェクトのKeyframeを作成します。
Our other option would have been to design
再生位置を動かし、キャラクターのパーツを動かして
a sprite sheet-based animation and design each
自動的にKeyframeを作ってアニメーションを作る事ができます。
each frame in Photoshop,
CurveとDopesheet、2つの表示を切り替える事で
an approach we use later for the background Swan,
タイミング及びデザインを調整も
which we'll discuss later in the video.
完成したアニメーションを
Because our character had independent elements
ステートマシーンを使って切り替える事が出来ます。
that we wish to animate we finalised the design
キャラクターのAnimator Controllerは bipedを使用していないので
and then moved his bodily elements in to separate
Apply Root Motionのチェックを解除して
spaces on our canvas to allow Unity to isolate them
Animate Physicsを有効にします。
as separate sprites in the Importer.
これで、物理エンジンで正しくアニメーションされる様になります。
This meant that we could then arrange all of
フィールド上を移動する為に
our sprites as separate elements to be animated.
プレイヤーの足元にはCircle Colliderがあります。
We placed these on to a new Character Sorting Layer
また、体を囲うBox Colliderもあります。
that we created, and then used Z values in the
これにより、段差をスムーズに乗り越える事ができ
transform to sort their rendering depth.
ジャンプの時は頭が天井にをぶつかるようになります。
All of these sprites are then arranged under an
キャラクターのアニメーションを制御するために、
empty game object, which has all of our
2Dフィジックスで動かすスクリプトを作りました。
controls scripting, colliders, physics, excetera attached to it.
フィジクスを使ってキャラクターと
Once we'd done this we were able to use the newly
敵を動かしてもっとダイナミックな
upgraded Animation window to create
ゲームプレーが可能になります。
Idle, Run, Jump, Shoot and Death animations
キャラクターのPlayerControlスクリプトでは
by animating each of the character's sprites over time.
プレイヤーの入力をチェックします。
With the new Dopesheet View in the Animation window
入力は物理制御を通してキャラクターを移動させ、
this is easier than ever.
また、この入力をAnimatorに渡し
We simply add animation to the parent object
ステートから正しいアニメーションを選択して
and then create keyframes for any of the child objects.
それぞれのアニメーション間をスムーズに遷移させます。
Moving the playhead to where we want
アニメーションからステートを作成すると便利な点は
and then moving the various parts of the character
物理の速度に応じてアニメーションの速度を変化させられる事です。
to automatically keyframe the animation.
速度に応じてアニメーションを切り替える必要はありません。
The ability to switch between Curve and Dopesheet
FixedUpdateという関数は物理更新の毎に呼び出されます。
representation of our animation makes it easier than
この関数で水平方向の入力を取得し、
ever to adjust timing and design.
AnimatorのSpeedパラメータに入れます。
With these animations created we can
ステートマシーンの待機と移動間の遷移条件は
then design a state machine for our character
Speedパラメータが0.1以上かどうか、になります。
so that when called upon in code, differing animations
その状況になると、アニメーターは待機のステートから
could be played.
移動のステートにブレンドします。
the animator controller for the character is
次は、プレイヤーのRigidbody2Dという2D物理要素に
not driving a 3D biped, so we simply deselect
力を加えてプレイヤーを動かします。
Apply Root Motion and select Animate Physics
キャラクターの向いている向きを制御するのにも
in order to drive our animations in time with
水平方向の入力を利用します。
the physics engine.
Unityでは、左キーを押すと-1が返り
In order to traverse the environment our hero has a
右キーを押すと+1が返ってきます。
circle collider at his feet and a box collider
入力された値に応じて、Flip()関数で
to cover the rest of his body outline.
キャラクターのXスケールを反転させて
This means he can smoothly walk up and down hills
反対側を向いている状態を表現します。
and when he jumps his head will hit the ceiling.
地面を接地しているかどうかを決めるために、
In order to control the character and it's animations
Groundというレーヤーを追加して
we wrote a script that moves him via 2D physics forces.
すべての歩ける地面に適用します。
This means that we can apply physics to him
そして2DのLinecastという関数を使い
and the enemies during the game for more
キャラクターの足元にGroundレイヤーがあるかどうかを
dynamic game play.
チェックできます。
In our PlayerControl script for the character
より簡単に変更できるようにするため、
we check for player input.
接地判定用の空のGameObjectを追加しました
We use this to apply physics forces
この空GameObjectにGizmoを追加する事で
for movement and also send the value of the input
接地判定の距離を調整できます。
to the animator, which in turn defines which
ゲーム中は
animation should be playing and smoothly transitions
キャラクターは地面に設置している状況でのみでジャンプできます。
between the different animation clips that
プレイヤーの制御の詳細は、
we've created as states.
スクリプトのコメントを確認してみてください。
The great thing about using the animator to
プレイヤーの攻撃に関しては後ほどお話したいと思います。
create states from animation clips is
次は、このデモで
that we can go and tweak speeds of animation
カメラがどのような動きをするか見てみましょう。
to match our physics velocities
2Dゲームにおいても、3Dゲームと変わらず
without having to reanimate anything
カメラの動作はとても重要です。
The FixedUpdate function evaluates with
古典的2Dアクションのカメラを学ぶために
each physics step, and the first thing we
スーパーファミコンのスーパーマリオワールドを見てみましょう。
do with this is to feed the value of Horizontal
スーパーマリオワールドでは
input in to the Speed parameter of our animator.
カメラは横方向に追従しますが
The transition between Idle and Run
画面の中心にはキャラクターに追従しない遊び幅があります。
in our simple state machine requires
この遊び幅の外側に動こうとすると
that the Speed parameter is above 0.1.
カメラはプレイヤーの位置に追従します。
When it is, the animator blends from Idle
高さ方向に対しては一定段階の高さを保ちますが、
in to the Run state.
我々のゲームに関してはその必要はありません。
We then go on to add forces to the player's
ステージの横幅はそれほど長くなく
2D physics component, the rigidbody2D,
殆どが画面に収まる広さのステージです。
in order to move him around.
ですので、カメラの水平の動きと垂直の動きは同じ動きにします。
We also handle which direction the character is facing
mainCameraのGameObjectに付属している
based on the value of Horizontal input,
CameraFollowというスクリプトを見てみましょう。
checking whether it is above or below 0.
どのような働きをするのか、コメントを確認してください。
This is because in Unity, holding the left input key
色々な機能の中で最も重要なことは
returns a value of -1, where right returns positive 1.
ヒーローの宇宙人を倒す能力です。
Depending on input, we then call a simple flip function,
ヒーローのバズーカは発砲後の反動アニメーションがあります。
which reverses the X scale of the character,
このアクションはいくつかの部分に分かれています。
giving him the appearance of facing the opposite direction.
Fireキーの入力があると
To decide whether the player is grounded
ロケットを発射して、オーディオを再生して
we added a layer in Unity called Ground
アニメーションステートを再生します。
and applied it to all of our walkable foreground surfaces.
もっと詳しく調べてみましょう。
We then used the Linecast function in 2D
Runや他のアニメーションの再生中に
to check whether something on the Ground layer
Shootアニメーションを再生するのため、
is below the character's feet.
Shootingという別のレイヤーを作成しました。
To customise this more easily we created
Weightプロパティを1にすると
an empty game object to use as a point
Shootingレイヤーに含まれるパーツは
at which to check for the ground.
ベースレイヤーの動きを完全に上書きします。
By adding a gizmo to this empty object
このレイヤーは、プログラムからShootトリガーを呼び出されると
we are able to manipulate how far below
いつでもShootアニメーションに切り替わります。
the character we'll check for the ground.
Gunスクリプトのこの機能を調べてみましょう。
From a gameplay perspective this means that
ここで、アニメーターを操作して
the character can only jump when grounded.
ShootトリガーをTrueにします。
Check out the rest of the comments in the script for more
トリガーはスイッチのように
information on the control of the player.
次のフレームにFalseに戻り、再び使用できるようになります。
We will discuss the player's weapon
これは攻撃のようなアクションにぴったりです。
later in this video.
アニメーションをセットし、
Next, let's take a look at how the camera
ロケットもこのスクリプトで発射します。
tracks the player in our demo.
オーディオを再生して
In 2D games, much like 3D, the motion of
プレイヤーの向いている方向に対して
the camera tracking the action can make
ロケットの速度を設定します。
or break your game.
このスクリプトはヒーローの
For a classic 2D platformer, we looked at the mechanics
Gunという空のGameObjectに付属します。
of one of the most interesting camera in 2D gaming history,
空のGameObjectにスクリプトを追加するのは、
the camera from Super Mario World on the Super Nintendo
簡単にロケットの発射位置を設定できるようにするためです。
or Super Famicom.
バズーカの先に空のGameObjectを配置して
In Super Mario world the camera tracks
オブジェクトの位置にロケットが生成されるようにします。
horizontally, but uses a dead zone
ロケットは2DRigidbodyを持って
or margin in the centre of the viewport
それに速度を与えて動かします。
in which the character can move a little
スプライトの排気炎を付け
without the camera tracking.
パーティクルシステムの煙も足します。
Once the character moved beyond this margin
パーティクルシステムも新たなスプライト版機能が追加されました。
the camera tracks back toward the player.
煙のコマが描かれたスプライトをマテリアルに追加する事で
The Super Mario World camera used particular heights
簡単にスプライトアニメーションのパーティクルを作成できます。
to snap to vertically, but we didn't need this
敵またはフィールドにロケットが当たると
kind of detail for our game as we
ロケットは消え
do not have a long level in the X axis
爆発が生成されます。
but more of a stage on which the action takes place.
爆発は単純なコマアニメーションを行うスプライトです。
For this reason our camera employs
Sorting Layerで前景の最後に描画されるようにします。
similar tracking vertically as it does horizontally.
このようなスプライトに基づいたアニメーションの追加は、
Take a look at the CameraFollow script on the
Project Panelからファイルを選んで
mainCamera game object to see comments
Sprite Modeを"Multiple"にします。
on how it achieves this effect.
これでスプライトエディタを使い
There are several effects in the game,
手動、もしくは自動的に分割する事ができます。
but most important is our heroes ability
ファイルをスプライトに設定する利点は、
to slay the alien onslaught he's faced with.
この様にApplyをクリックするだけで
Our hero shoots a bazooka which has animated recoil.
Unityはファイルの子供としてそれぞれのスプライトを生成し
This action is made up of several parts.
そのスプライトをそのまま使う事が出来ます。
First we listen for key input and when the Fire key is
これがロケットの構造です。
pressed we instantiate a rocket,
どのようにして敵を倒すのかは、
play an audio clip and trigger an animation state to play.
後ほど敵の項目でお話したいと思います。
Let's break this down even further.
話をプレイヤーキャラクターに戻して
in order to play the Shoot animation while other
HPとダメージのことを調べましょう。
animations such as Run are playing we
HPはfloatとして保存されています。
created a separate layer within our animator
敵からのダメージはTakeDamage関数を呼び出して与えます。
called Shooting.
プレイヤーが簡単に倒されてしまうのを避けるため、
By setting the Weight property to 1 here
前回のダメージからrepeatDamagePeriodが経過した場合のみ
we can totally override motion in the base layer
ダメージを受けます。
on any parts of our character that are animated
また、敵から逃げ易くするため、
by clips on the shooting layer.
そしてプレイヤーのダメージを表現するため、
In this layer we switch to the Shoot animation
ダメージを受けたキャラクターをヒットバックさせます。
from any state, when the Shoot trigger
TakeDamage関数で一時的にプレイヤーのジャンプを止め、
parameter is called from code.
敵からキャラクターへの方向に物理的な力を与えて動かします。
Let's take a look at the Gun script in charge of this.
hurtForceの変数はInspectorで表示しているので、
Here you can see that we address the animator
スクリプトを編集せずにゲーム要素の調整が出来ます。
and set that trigger to True.
ダメージ表現に加えて
Triggers simply act as a switch and reset themselves to false
もちろんプレイヤーのHPも減らした上で
on the next frame so that they can be called again,
HPバーを更新します。
which is perfect for actions such as shooting.
HPの差を表示するのためにバーの長さを縮め
In addition to setting the animation we fire the
色を緑から赤に補間します。
rockets themselves from this script,
最大HPに対する現在のHPの比率を計算すれば出来ますね。
playing an audio clip and dependent upon
HPバーはシンプルなスプライト2つで構成されています。
the direction that the player is facing
バーの外周部分とバーの部分です。
we instantiate a rocket and give it a velocity
これらもPhotoshopでデザインして
that's positive or negative in the X axis.
2つのテクスチャを書き出しました。
This script is attached to the Gun empty game object
このスプライトのImport Settingsで
in the hero's hierarchy.
Pivotを左の中央に設定して
We place code like this on to an empty game object
スケールを小さくした時に左側に縮んでいく様にします。
as it allows us to easily position
この2つのスプライトは
where the rockets are created.
プレイヤーに追従するスクリプトを追加した
We do this by placing the empty object
空のGameObjectの子供として配置します。
at the end of the barrel of the bazooka
プレイヤーのGameObjectの位置とオフセットを足すので
and then we use it's own position as the
表示位置はInspectorで調整できます。
point at which to spawn the rockets.
プレイヤーは残りHPが0になると
The rocket itself has a 2D rigidbody
コライダーをトリガーモードに設定されるので
and we assign a velocity to that in order
プレイヤーはステージを突き破って落ちます。
to make it move.
その時、最前面に描画される様に
It has a sprite swap flame exhaust
SpriteRendererを”UI”ソートレイヤーに移動させます。
plus a particle system for smoke.
プレイヤーの死亡アニメーションは、2段階で構成されます。
The particle system also accepts the new sprite type of graphics
最初の”Death”は、帽子と武器を落とします。
so by adding a sprite sheet of smoke puffs
2番目は”Falling”という名前です。
to a material we can assign it to the
アニメータにExit Timeのコンディションを使って
texture sheet animation module of the particle system
”Death”アニメーションが終わると
and we get instant animation of our
自動的に”Falling”に遷移します。
sprites for the particle emission.
最後に、プレイヤの動きと攻撃を停止させるために
When our rockets hit an enemy or part of the environment
PlayerControlとGunのスクリプトを無効にします。
the rocket itself is destroyed and
Die関数はPublicなので
an explosion is spawned.
どこからでも呼び出せます。
The explosion is simply a sprite game object
例えば、水に落ちた時。
that animates through a sprite sheet that we have created.
プレイヤーが水に落ちるとゲームをリセットするために、
Yet again using sorting layers to render this
トリガーコライダーとスクリプトだけがある
at the lowest layer order of our foreground objects.
KillTriggerという名前のGameObjectがあります。
When adding sprite-based animation like this
Removerスクリプトには
we setup the sprites themselves by
川にザブンと飛び込んだ敵を消して
selecting the file in our Project Panel
飛沫のアニメーションとサウンドを再生する役割があります。
and choosing the Sprite Mode Multiple.
しかしこのコライダーにプレイヤーが衝突すると
This gives us access to the sprite editor
PlayerHealthスクリプトの”Die”関数呼び出して
which allows us to slice manually or automatically.
プレイヤーを画面外に動かしている間カメラの追従を無効にし、
Once happy with the selection of sprites from our file
2秒後にステージをリセットするコルーチンを実行します。
we simply hit Apply and Unity
さて、プレイヤーキャラクターの死について考えるのではなく、
generates the sprites as children of that file
彼が生き残るために何をあげればいいかを考えましょう。
to be used in our project.
このゲームでは2種類のプレイヤーを助けるアイテムボックスが落下してきます。
So that's our rocket in a nutshell.
一つは爆弾、もう一つは救急箱です。
We will discuss the mechanics of killing the enemies
このアイテムは2つの部分で構成されています。
later in this video in the section about enemies.
箱本体と落下傘の部分です。
Let's return to the player character now and look at
これらの要素は空のオブジェクトでグループにして動かす事ができます。
how we handle health and taking damage.
落下傘の中心を親オブジェクトの中心に位置します。
Health is stored as a float and
これで箱を、落下中左右に揺れるようにできます。
with each interaction with a tagged enemy
オブジェクトが落下させる為には
we call the TakeDamage function.
単にRigidbodyを追加するだけです。
This is only allowed to occur after the
そして、箱の着地やプレイヤーの取得を検出する為に
repeatDamagePeriod has passed
コライダーも追加します。
to avoid the player being killed very quickly.
箱が着陸したら
To allow the player to escape enemies more easily
落下傘をしぼませるステートに遷移します。
and to show the player that they are being hurt
他のアニメータと同じ様に
we make the act of taking damage
アニメーターはオブジェクトのステートを管理しています。
repel the character physically.
デフォルトではfloatDownステートですが
To achieve this the TakeDamage function briefly
LandトリガーがTrueになると着陸のステートに切り替わります。
stops the player from jumping
この処理はスクリプトのonTriggerEnter関数で実行しています。
and finds a vector from the enemy to the player
タグで地面を見て地面かどうかを判断しています。
and repels him in that direction
箱を親オブジェクトからデタッチし、
by adding a physics force.
Rigidbodyを追加します。
The hurtForce variable is exposed in the Inspector
それにより、地形の影響を受け
as public so that it can be tweaked
斜面に着陸した場合でも正しい角度で停止します。
to adjust this element of game play without
さて、爆弾を見てみましょう。
returning to the script.
爆弾を取得する処理は
In addition to repelling the player,
箱に付属したBombPickupスクリプトで行われます。
we of course subtract from the player's health.
爆弾を拾うと、箱を消して
and update the player's health bar.
プレイヤーに付属したLayBombsスクリプト内の
To signify the decrease in health we subtract
爆弾を持つ数を加算します。
from the width of the bar and use a colour lerp
LayBombsのスクリプトは
to transition it's colour between green and red,
プレイヤーが爆弾を持っているかどうかをチェックして
both by finding the percentage that the current health is
BombのPrefabを生成します。
of the full health amount.
BombのPrefabはBombDetonationというcoroutineで
The health bar simply comprises of two sprites,
待ってExplode関数を呼び出します。
one for the outline of the bar and the other
Explode関数は様々な動作があります。
for the bar itself.
まず、他の爆弾が出現できる様にするため
This was again designed in Photoshop and then
変数bombLaidをリセットします。
the two separate elements were exported.
そしてアイテム管理に新しい箱が追加可能な事を通知し
In the import settings for these sprites
範囲内にいる全ての敵を倒します。
we set their pivot to the middle left of the graphic
最後の部分がどのような働きをするのか注目して下さい。
so that when it scales down it shrinks towards the left.
残りHPに関係なく全ての敵を倒すために
These two sprites are placed under an empty
Physics.OverlapCircleAllを使って
parent game object which has a simple script
全てのEnemyタグが付けられたオブジェクトを取得します。
on it which makes it follow the player.
foreachループで見つかった全ての敵のHPを0にして
We do this by setting the position to the
爆弾から敵の方向に吹き飛ばします。
same as the player object's position
ループが終わったら
plus an offset that we've made public to allow
エフェクトを再生し 爆発の効果音を再生して
for adjustment in the Inspector.
爆弾を消去します。
When the player has 0 health remaining
爆発には2つの要素で構成されています。
we allow him to fall through the level by
主な部分は、一時的に登場して消える丸です。
setting his colliders to triggers,
2番目の部分はロケットの爆発のスプライトを再利用した
and we move him to the very front of rendering
星のパーティクルです。
by placing his sprite renderers on the UI Sorting layer,
効率よくこのパーティクルを使用するために
one we've made to render in front of everything in the game.
常にシーンに配置しておき
We have 2 animations for when the player dies.
表示させたいタイミングで表示位置に動かして再生します。
1 called Death, where he loses his hat and gun
メモリにパーティクルを常駐させる事で効率が良くなります。
and another called Falling.
これは、プレイヤーは1つしか爆弾を持てない、
We naturally transition in to Falling once
つまり爆発も1つしか表示されないので出来る事です。
the Death animation completes by using the Exit Time
パーティクルを常駐させておくことで
as our transition condition in the animator.
毎回パーティクルのインスタンスを生成して削除するよりも効率的です。
Finally, to stop the player moving the character
ですが、ロケットの爆発は一度にたくさん出る事があるので
or shooting during the Death sequence
毎回生成と削除する事が必要です。
we disable the PlayerControl and Gun scripts.
プレイヤーが敵を倒してポイントを得る処理を見てみましょう。
Because the Die function is made as public
これは2つのパーツでできています。
we can call it from elsewhere, such as if the player
プレイヤーが100ポイントを獲得した表示と
falls in to the water.
画面の上に表示されているスコアーが加算されてゆくUIです。
To reset the game once the player does hit the water
得点のアニメーションは1と0のスプライトで構成されています。
we have a KillTrigger object, which simply
空のオブジェクトの子として配置し
comprises of a trigger collider and a script.
アニメーションが終わると簡単なスクリプトで
For most of the game the purpose of the Remover script
シーンから削除されます。
is to remove our enemy objects that fall in
アニメーションの最後にイベントを追加し
to the river, and instantiate a splash animation
スクリプトの削除関数を呼び出します。
and sound effect.
ScoreUIは、カスタムフォントと
However, when the player is detected by this trigger
プレイヤーの得点を管理するスクリプト付属された
we call the Die function in the PlayerHealth script
シンプルなGUIコンポーネントです。
and also disable CameraTracking
Scoreはパブリック変数です。
whilst moving the player off screen
なので敵が倒された時、
and calling a co-routiene that pauses for 2 seconds
Enemyのスクリプトからポイントを追加する事ができます。
and then reloads the level.
さて、今度は敵の話です。 詳細を見てみましょう。
But let's not dwell on the death of the player,
このゲームには2種類の敵が登場します。
let's look at his survival and the tools that we give
緑のナメクジモンスターと
him to do that.
宇宙船に乗った宇宙人です。
Our game features 2 airdropped crates that
挙動はほぼ同じなので同じスクリプトを使い回し、
assist the player, 1 containing a bomb,
Inspectorから移動速度とHPを調整して差を付けています。
the other a med kit to boost health.
各敵はそれぞれのWalkアニメーションがあります。
These crate drops are made up of 2 parts.
ナメクジには動く尾があり
The crate itself and a parachute.
宇宙船の敵は行ったり来たりします。
These 2 elements are nested beneath an empty parent object
ナメクジの尾の部分は
to allow us to animate them as a group.
スプライトインポータで独立したパーツとしてインポートしました。
We position the 2 sprites so that the parachute's
なので、尾の部分を独立して動かす事ができ、
centre is at the centre of the parent.
スプライト全体が伸び縮みししないようになっています。
This way the animation can swing left and right
Pivotを右にする事で
as if the entire parachuting crate is floating to the ground.
そこから尾が伸び縮みするアニメーションをつけます。
We then simply add a rigidbody to cause
まぶたを上下に動かして
gravity to pull the object down
Z値でスプライトがソートされるようにし
and add colliders to the crate so that
目がまぶたの下に表示されるようにします。
we can detect when it lands and when
次の敵はかなりシンプルです。
the player picks up the crate.
行ったり来たりを繰り返すアニメーションにします。
Upon landing we transition to a second
敵の動きには、Rigidbodyの速度をセットします。
animation state which scales the parachute down.
宇宙船が障害物、例えば壁等への衝突は
Like other parts of our game, the animator handles
ある点がコライダーと重なっているかどうかを
the states of the object.
Physics.OverlapPoint関数を用いて検知します。
We can see that by default it plays the
障害物、このステージ両端のタワーは
floatDown animation state
障害物としてタグが設定されています。
but then switches to a landing state
衝突を検知するとFlip関数を呼び出して
when the trigger Land is set to true.
敵のXスケールを反対にして反対方向に向かわせます。
In our script we do this using an onTriggerEnter function,
敵を倒す判定のために、
which detects the ground via a tag.
ロケットが敵に当たる度にHurt関数を呼び出します。
We also detatch the crate itself from the parent object
この関数の内部では、敵のHPを1づつ下げています。
and give it a rigidbody of it's own
FixedUpdate関数の中で敵のHPを監視しており、
so that it can interact with the environment
0になっている場合はDeath関数が呼び出されます。
resting realistically on a slope if it lands on one.
敵が死亡する時には様々な処理が実行されます。
Let's focus on the bomb first of all.
まず、2Dのキャラクターの全てのスプライトを非表示にします。
Picking up the bomb crate is handled on the
これは、アニメーションのためにある複数のスプライトを
BombPickup script, attached to the crate.
1つの死亡したキャラクターのスプライトに差し替えたいからです。
We pickup the crate by destroying it and adding to
メインのSprite RendererにdeadEnemyのスプライトを設定します。
the count of bombs that the player has
Scoreスクリプトのパブリック変数に対し スコアを加算します。
in the script attached to the player called
敵の死亡のビジュアルをわかりやすくするため
LayBombs
Rigidbodyにトルクを追加して回転させます。
The LayBombs script simply checks if
背景を突き抜けて川に落下させたいので
the player is carrying a bomb
すべてのコライダーを探して
and then instantiates an instance
IsTriggerパラメーターをTrueにします。
of the Bomb prefab.
これで背景のコライダーを突き抜ける事になります。
The Bomb prefab has a timed fuse
死亡時に再生するオーディオクリップ中の1つを選び再生し
which waits by using an yield within the
前述の得点表示アニメーションを再生します。
BombDetonation co-routiene
敵をシーンから削除するため、
before calling the Explode function.
KillTriggerオブジェクトを使います。
The Explode function performs several actions.
これは先ほど説明した通り、 水しぶきをあげオブジェクトを消去する機能を持ちます。
First it resets the bombLaid variable
プレイヤー以外のオブジェクトが触ると
to allow another bomb to be deployed,
水しぶきのエフェクトを表示して オブジェクトを削除します。
it tells the pickup spawner it is allowed to
効果音は水しぶきエフェクトが表示される時に
spawn a new crate drop and kills
付属しているAudio Clipが同時に再生されます。
enemies within a defined blast radian.
なので、オブジェクトを生成するだけで
Let's take a look at how this last part works.
効果音も鳴るようになっています。
Because bombs are lethal to enemies regardless of
動的なオブジェクトを追加し
their remaining hit points we use the
背景を飾ってステージを完成させましょう。
Physics.OverlapCircleAll to collect all objects
飛んでいる白鳥と
tagged Enemy within a certain radius of the bomb.
川岸を走るバスとタクシーを追加します。
We then run a foreach loop for every enemy found
まずは白鳥のスプライトシートをPhotoshopで描いて
setting their health to 0 finding a vector from where the bomb was
InspectorのMultiple Sprite Modeを使ってインポートしました。
to where the enemy is, in order to apply
この方法では
a force in the direction of that vector.
Unityが全てのコマを選択し自動的にインポートして
Once the foreach loop is complete
アセットのヒエラルキーに追加してくれます。
we play and instantiate visual effects,
このコマは連続したアニメーションのセットなので、
play an audio clip for the explosion
全てのコマをシーンにドラッグするだけで
and of course destroy the bomb itself.
Unityが自動的にアニメーションさせてくれます。
The visual of the explosion is twofold.
ね、簡単でしょ?
The main part is a simple circle that appears
白鳥は背景に追加します。
briefly and is then destroyed
速度を与えて画面中を動けるように
and the second part is a particle system of
Rigidbody2Dを追加します。
stars that reuses the same sprites
バスとタクシーのように、白鳥もPrefabです。
as our rocket explosion.
バスとタクシーのPrefabには、
For efficiency we keep this particle
Sprite Importerで車体とタイヤを分割して
system in the scene at all times
シンプルなアニメーションを生成します。
and when it is required we use code
これらにもRigidbody2Dを追加して
to move the system to the desired position and play it.
速度の追加で画面内を動かす事ができます。
This keeps the particle system in memory
白鳥、バス、タクシー
and makes the game more efficient.
この3種のオブジェクトの生成を
It's worth noting that we can do this
管理するスクリプトを作成してあります。
because we know we will only have 1
BackgroundPropsSpawnerスクリプトは
single explosion in the scene at any one time
頻度、速度、そして最初の位置を管理しています。
as the player can only throw 1 bomb at a time.
3種のオブジェクトに同じスクリプトを使うことができます。
This is why keeping our particle system in the
生成するPrefabとプロパティを変更します。
scene and replaying it is more
詳細は、スクリプトのコメントをご覧ください。
efficient than creating instances and then removing them.
最後に、動いている雲、川の流れ、そして霧を追加しました。
With the rocket explosion however,
親オブジェクトに2つのスプライトを持たせ、
we can have many at once so we do
ゆっくりと横に動かします。
need to spawn and remove them.
アニメーションはループで動き続けます。
Now let's take a look at what happens when our player
以上が、私たちがどのようにしてこのゲームを作ったか、の全てです。
kills an enemy and scores points.
このビデオが2Dゲームの作り方の参考になれば嬉しく思います。
This is done in 2 parts,
将来的には、より基本的なプロジェクトと
a scoring animation that plays showing 100 points earned
チュートリアルをお届けしたいと考えています。
and the score UI at the top of the screen
私達は、Unity4.3についての感想と
that increments.
あなたの作る素晴らしい2Dゲームが本当に楽しみです。
The score animation is made up to 2 number sprites,
それでは、ご清聴ありがとうございました!
a 1 and a 0.
We place this in the scene under an empty parent object
and animated them using a simple destroyer script to
remove them from the scene when the animation is complete.
We call the destroyer function in the script
by placing an animation event
at the end of the timeline.
The ScoreUI itself is a simple GUI text component
with a custom font and script that manages
the score for the player.
The Score variable is public, meaning that we can address it
from the Enemy script when they are killed
and add 100 points to the value.
Speaking of the enemies, let's take a look
at them more in depth now.
In our game we have 2 types of alien enemy,
a green slug-like monster and a smarter
alien that brought his ship with him for
protection during the invasion.
These characters share the same script
as the behaviour is very similar
and we allow for differing movement speeds
and amounts of hit points by setting
these as public variables in the Inspector.
Each enemy has it's own Walk animation.
The slug has a moving tail, whist the
ship-based enemy rocks back and forth as it approaches.
For the slug we used the sprite importer
to define the tail section of the graphic
as a separate sprite element,
meaning that we could animate it individually
and avoid having to scale the entire sprite.
By setting the pivot to the right
we are able to animate the tail expanding and contracting
from that point.
For added character we then move the eyelid up and down
and we use the Z value to sort the sprites
amongst one another, the eye being below the eyelid
so that we could animate it over the top.
The second enemy's animation was much simpler
and just meant that we rotated it back and forth.
For the mechanics of moving the enemies
we drive them by setting the velocity of the rigidbody.
When they encounter an obstacle such as a wall
they detect this by using a Physics.OverlapPoint function,
which checks for a point in space overlapping a collider.
Our walls, the towers at each side of the level,
are tagged as obstacles.
When this function detects them it calls the Flip function,
it reverses the X scale of the enemy
sending them moving in a different direction.
To kill the enemies, each time a rocket collides
with them it's script calls the Hurt function on
the particular enemy that it's hit.
In this function we subtract 1 from the
hit points of the particular enemy.
We then keep tabs on the enemy's health
inside the fixed update function.
If it drops to 0 we call the Death function.
When they die we perform a number of functions.
Firstly we disable all sprite renderers
as our 2D characters are made up of a
number of sprite objects that are animated.
This is because we simply want to swap out the
animated elements for a single sprite
of the dead character
We do this with the main sprite renderer by
setting it to use the sprite assigned to
the deadEnemy variable.
We then add to the score using the public
variable in the Score script
and we add some visual flare to the enemy's death
by adding torque to spin them as they die.
Because we need the enemies to fall through the
environment and land in the river when they die
we find all colliders on the object
and set their IsTrigger parameter to true.
This means that they will pass through the
environment colliders.
We then choose from an array of death audio clips
and play one of them back, before creating
an instance of the Score animation we showed you earlier.
To remove the dead enemy from the scene
we rely on the killTrigger object
It performs the same function as discussed earlier
as any non-player object touching it
will cause a splash animation and remove that object.
The sound effect of them hitting the water is
an audio clip attached to the animated
splash which plays on awake
so that when we create an instance of the animated
object we hear the sound right away.
To finish the game level re decorated the
background with a number of moving props
in order to make our game environment feel more dynamic.
We added flying swans, plus buses and taxis that drive
along the river bank.
First was the swan, which was created from a sprite sheet,
drawn in Photoshop and imported using
the Multiple Sprite Mode import setting
in the Inspector.
By choosing this approach Unity automates choosing
each frame in the sheet and importing
it as a separate sprite under the parent
hierarchy of the asset.
Because this is a linear set of animation frames
we could simply drag all of these sprites in to the
scene to let Unity animate them for us.
Et voila, our animated swan is ready to add
as a background element.
The swan was then given a rigidbody2D
so that we can use velocity to send it
across the screen.
As with the bus and the cab, the swan is saved as a prefab.
For the bus and taxi prefabs we
simply separated the bodies and wheels of
the vehicles in the sprite importer
and made a simple bobbing animation.
Applying a 2d rigidbody to these as well,
we were able to drive them across the screen
using velocity.
For all 3 props, the bus, taxi and the swan
we created a script we could reuse
which is in charge of spawning them.
The BackgroundPropsSpawner script
also handles the frequency, a speed to give them
and where on screen to spawn them.
This meant that we could make 3 creator objects
with the same script on.
Changing which prefab will be spawned
and what properties to give it.
Take a look at the comments in the script to learn more.
Finally, for more background dynamism,
we added rolling clouds, panning river details and fog.
We did this by adding 2 instances of the background sprite
to a parent object and simply used animation to slowly
pan them across the screen.
Because this animation loops our animation will
continue indefinitely.
And that's how we made our game.
We hope this overview has given you some idea of
how we create 2D games in Unity,
and we'll be creating more simply projects and
tutorials in the future.
We look forward to your feedback on Unity4.3
and we can't wait to see the great 2D titles
that you'll come up with.
Thanks for watching.