SlideShare a Scribd company logo
1 of 43
Download to read offline
©makohira2013
第2回Unity初心者勉強会
2013.6.4
by makohira
©makohira2013
自己紹介開発者名:makohira(本名:山平誠)
住所:愛知県尾張旭市
  facebook.com/Makoto.Yamahira
  @makohira
普段の仕事:業務系SE
家で:スマホアプリ開発(Android, iPhone)
趣味:英語、飲み会、カラオケ・・・
最近よく行く所
レガーレカフェ栄(http://www.legarecafe.com)
名古屋iPhone開発者勉強会(https://www.facebook.com/iDevNagoya)
その他
実はまだUnity初心者です。
自分の勉強とモチベーション維持のため定期的にUnity初心者勉強会を開催しています。(愛知県名古屋市で)
今のところ非公開のイベントにしていますが、興味のある方は連絡ください。
©makohira2013
英文法クエスト
https://itunes.apple.com/us/app/ying-wen-fakuesuto/id596772964?l=ja&ls=1&mt=8
RPGで遊びながら英文法を勉強するiPhoneアプリです。
(...すいません。Unityではなくcocos2dで作りました。)
おかげさまで2013年3月18日にAppStore有料教育カテゴリで1位になりました^^
代表アプリ
©makohira2013
本日の目標
横スクロールアクションゲームを作ってみる。
©makohira2013
TestGame02
主人公は常に右に進む。スペースバーを押すとジャンプ。
敵は左に向かって進む。 コインをとれる。
ゴールのシリンダーに触るとゲームクリア。
©makohira2013
何が必要?
1. ライトを追加する
2. 床を作る
3. Playerを作る
4. カメラを調整する
5. Goalを作る
6. 敵を作る
7. コインを作る
8. コインをとれるようにする
9. 表示を作る
作りたいゲームがイメージできたら、必要なオブジ
ェクトを作っていきましょう。
©makohira2013
1.ライトを追加する
とりあえず画面が暗いと困るので、
「Directional Light」を追加しましょう。
画面が明るくなります。
©makohira2013
2.床を作る
床は必要だよね。
1.Cubeオブジェクトを追加しよう。
2.名前をFloorに変えよう。
3.PositionのZ値を0にしよう。
4.ScaleのXを調整しよう。
5.Prefab化しよう。
6.Prefabを利用してたくさん床をつくろう。
©makohira2013
こんな感じになりました。
©makohira2013
3.Playerを作る
Playerを作ります。
今回は物理的な動きをさせたいので、
「Rigidbody」コンポーネントを使います。
まず、次の手順でPlayerを作ってください。
1.Cubeを追加
2.名前をPlayerに変更
3.位置をちょうど良い場所に移動
4.「Rigidbody」コンポーネントを追加
5.「PlayerScript」を作り、Playerに追加
©makohira2013
Rigidbodyコンポーネントについて①
Rigidbodyコンポーネントを追加すると
オブジェクトは物理制御を受けるようになります。
インスペクタの値を色々触ってみると挙動が変化するのが
分かると思います。
今回は、
Constraintsの
Freeze Positionのz
Freeze Rotationのx, y, z
にチェックを入れておきましょう。
これにより、何か他の物に当たったとしても
Positionのz値は変わらず、回転もしなくなります。
©makohira2013
Rigidbodyコンポーネントについて②
Rigidbodyコンポーネントを追加すると
スクリプトで次のようなコードを利用できるようになります。
rigidbody.AddForce(Vector3の値)
意味:物体に力を与える。
力を与えられたオブジェクトは物理制御の元で勝手に動きます。
普通にtransformコンポーネントを使って動かすことも
もちろん可能です。
©makohira2013
ユーザー入力の取得について
UnityではInputクラスがユーザー入力を管理しています。
メニューバーの[Edit]-[Project Settings]-[Input]で設定できます。
Input.GetAxis()で軸の状態を取得できます。
float value = Input.GetAxis(“Horizontal”);
float value = Input.GetAxis(“Vertical”);
Input.GetButton()で入力のイベントのみを取得できます。
bool value = Input.GetButton(“Jump”);
Input.GetKey()で任意のキー入力を取得できます。
bool value = Input.GetKey(“j”);
←水平軸の値
←垂直軸の値
←Input Managerで”Jump”に
割り当てられたキー
←キーボードの「j」キー
©makohira2013
Raycastについて
Playerがジャンプできるのは床の上にいる時だけにしたいです。
色々な方法があると思いますが、
今回は「Raycast」という機能を使ってみました。
「Raycast」はある一点から指定した方向に見えない線を出し、
その線と他の物体との衝突を検出できます。
Physics.Raycast(線のスタート位置, 方向, 距離)
のように使います。
返り値はbool値です。
(衝突した物体を取得できるオーバーロードもあります。)
©makohira2013
Playerと床との接触距離について
Unityの当たり判定はcolliderコンポーネントを使って計算します。
colliderには色々種類があります。
BoxCollider:箱形のコライダー
SphereCollider:球体状のコライダー
CapsuleCollider:カプセル状のコライダー
MeshCollider:3Dポリゴン形状に沿ったコライダー
等
今回のPlayerはBoxColliderを持っているので、
gameObject.GetComponent<BoxCollider>()
で取得したコライダーより距離を計算してみました。
©makohira2013
1 using UnityEngine;
2 using System.Collections;
3
4 public class PlayerScript : MonoBehaviour {
5
6 // パブリックなメンバ変数
7 public int Speed = 10; // 右向きのスピード
8 public int JumpPower = 50; // ジャンプ力
9
10 // Use this for initialization
11 void Start () {
12
13 }
14
15 // Update is called once per frame
16 void Update () {
17 // 常に右に移動
18 transform.Translate(Vector3.right * Time.deltaTime * Speed);
19
20 // ジャンプの実装
21 if (Input.GetButton("Jump")) {
22 // コライダーよりPlayerと床の距離を計算
23 float sizeY = gameObject.GetComponent<BoxCollider>().size.y;
24
25 // レイキャストで接地の判定
26 if (Physics.Raycast(transform.position, Vector3.down, sizeY)) {
27 // Playerに上向きの力を与える
28 rigidbody.AddForce(Vector3.up * JumpPower);
29 }
30 }
31 }
32 }
「PlayerScript.cs」のコード例です。
©makohira2013
実行してみましょう。
Playerは右に進んでいき、
「スペースキー」でジャンプできます。
でもすぐに画面から消えてしまいますね。
©makohira2013
4.カメラを調整する
カメラがPlayerを追いかけるようにしてみましょう。
ホントはカメラを動かすスクリプトを書いた方が
良いかもしれませんが、今回は簡易的な方法で実現
してみます。
©makohira2013
オブジェクトの階層関係を利用してみます。
「Main Camera」オブジェクトを
「Player」オブジェクトの子供にしてみましょう。
←「Main Camera」を「Player」にドラッグ&ドロップ
こうなればOK→
©makohira2013
実行してみましょう。
カメラがPlayerを追いかけるようになりました。
©makohira2013
5.ゴールをつくる
Goalを作ります。
Goalに触った時の処理は「PlayerScript」に
書くことにします。
1.Cylinderを追加
2.名前をGoalに変更
3.大きさと位置を調整
4.「PlayerScript」に衝突時の処理を書く
©makohira2013
CylinderでGoalを作る
©makohira2013
33 // 衝突時の処理
34 void OnCollisionEnter(Collision collision) {
35 switch (collision.gameObject.name) {
36 case "Goal":
37 Time.timeScale = 0;
38 break;
39 }
40 }
「PlayerScript」に追加するコードです。
今回はゴールに触ったら一時停止状態にするようにしました。
Time.timeScaleの値でゲーム時間の流れを制御できます。
   Time.timeScale = 1 ← 通常
   Time.timeScale = 2.5f ← 2.5倍速
   Time.timeScale = 0 ← 停止状態
©makohira2013
実行してみましょう。
「Player」が「Goal」に衝突するとゲーム停止状態
になればOKです。
©makohira2013
6.敵をつくる
敵をつくってみましょう。
1.Sphereオブジェクトを追加しよう。
2.名前をEnemyに変えよう。
3.PositionのZ値を0にしよう。
4.Rigidbodyを追加しよう。
5.「EnemyScript」を作成し、Enemyに追加しよう。
6.Prefab化しよう。
7.Prefabを利用してたくさん敵をつくろう。
8.「PlayerScript」にPlayerとの衝突時の処理を書こう。
©makohira2013
1 using UnityEngine;
2 using System.Collections;
3
4 public class EnemyScript : MonoBehaviour {
5
6 // パブリックなメンバ変数
7 public int Speed = 5;
8
9 // プライベートなメンバ変数
10 private float startDistance = 10.0f; // Playerとの距離がこの値以下になった時にEnemyを動かし始める
11 private bool isStarted = false; // Enemyが動き始めたかどうかのフラグ
12 private GameObject playerObj; // Playerオブジェクト
13
14 // Use this for initialization
15 void Start () {
16 // Playerオブジェクトの参照を変数に格納
17 playerObj = GameObject.Find("Player");
18 }
19
20 // Update is called once per frame
21 void Update () {
22 if (isStarted) {
23 // 左に移動
24 transform.Translate(Vector3.left * Time.deltaTime * Speed);
25 } else {
26 if (transform.position.x - playerObj.transform.position.x < startDistance) {
27 // Playerに近づいたらEnemyを動かし始める
28 isStarted = true;
29 }
30 }
31 }
32 }
「EnemyScript.cs」のコード例です。
©makohira2013
33 // 衝突時の処理
34 void OnCollisionEnter(Collision collision) {
35 switch (collision.gameObject.name) {
36 case "Goal":
37 Time.timeScale = 0;
38 break;
39 case "Enemy":
40 Time.timeScale = 0;
41 break;
42 }
43 }
「PlayerScript.cs」の衝突処理のコード例です。
←追加
©makohira2013
実行してみましょう。
「Enemy」が左に動きます。
当たったら一時停止状態になります。
©makohira2013
7.コインをつくる
コインをつくってみましょう。
1.Cylinderオブジェクトを追加しよう。
2.名前をCoinに変えよう。
3.PositionのZ値を0にしよう。
4.サイズと向きを調整してコインっぽくしてみよう。
5.コインに色をつけてみよう。
6.「CoinScript」を作成し、Coinに追加しよう。
7.Prefab化しよう。
8.Prefabを利用してたくさんコインをつくろう。
©makohira2013
コインに色をつける方法
オブジェクトに色をつけたい時は次のように操作します。
1. プロジェクトビューで右クリックし[Create]-[Material]を選ぶ
2. インスペクタで色を選ぶ
3. 出来上がったMaterialを色をつけたいオブジェクトにドラッグ&ドロップ
←1.追加
←2.クリック
←3.色を指定4.色をつけたいオブジェク
トにドラッグ&ドロップ→
©makohira2013
1 using UnityEngine;
2 using System.Collections;
3
4 public class CoinScript : MonoBehaviour {
5
6 // パブリックなメンバ変数
7 public int RotateSpeed = 10;
8
9 // Use this for initialization
10 void Start () {
11
12 }
13
14 // Update is called once per frame
15 void Update () {
16 // コインを回転させる
17 transform.Rotate(Vector3.up * Time.deltaTime * RotateSpeed, Space.World);
18 }
19 }
「CoinScript.cs」のコード例です。
transform.Rotateの第2引数には回転の基準となる座標系を指定します
 Space.World : ワールド座標系
 Space.Self : ローカル座標系
©makohira2013
実行してみましょう。
コインが表示されました。
©makohira2013
8.コインをとれるようにする
コインをとれるようにしましょう。
1.取ったコインの数を管理するためのオブジェクトを作る
2.コインを取る処理の実装をする
©makohira2013
コインを管理するためのオブジェクトを作る
1.メニューから「GameObject」-「Create Empty」を選択
2.名前を「GameManager」に変更
3.「GameManagerScript」を作成し、「GameManager」に追加
4.「GameManagerScript」にコイン数を保持するための変数を定義する
©makohira2013
1 using UnityEngine;
2 using System.Collections;
3
4 public class GameManagerScript : MonoBehaviour {
5
6 // パブリックなメンバ変数
7 public int Coins = 0; // 取ったコイン数を保持
8
9 // Use this for initialization
10 void Start () {
11
12 }
13
14 // Update is called once per frame
15 void Update () {
16
17 }
18 }
「GameManagerScript.cs」のコード例です。
©makohira2013
コインを取る処理を実装
コインを取る処理を実装します。
今回はUnityのトリガー機能を使って実装してみます。
「Coin」プレハブを選択してインスペクタをみると、
「Capsule Collider」のところに「Is Trigger」という項目があります。
このチェックを入れてください。
こうすると「Player」との「衝突」が「トリガー」に変わります。
このチェックが有るのと無いのとで物体同士がぶつかった時の動きが変わります。
「衝突」:物体はぶつかり、角度が変わったり減速したりします。
「トリガー」:検出のみ行われ、物体同士はすり抜けます。
「衝突」はOnCollision系のメソッドに処理を書きますが、
「トリガー」はOnTrigger系のメソッドに処理を書きます。
今回は「PlayerScript」に処理を書いてみます。
©makohira2013
45 // トリガーの処理
46 void OnTriggerEnter(Collider other) {
47 switch (other.gameObject.name) {
48 case "Coin":
49 // Coinの取得
50 GameManagerScript gameManagerScript = GameObject.Find("GameManager").GetComponent<GameManagerScript>();
51 gameManagerScript.Coins++;
52
53 // Coinを消す
54 Destroy(other.gameObject);
55 break;
56 }
57 }
「PlayerScript.cs」のトリガー処理の実装例です。
©makohira2013
実行してみましょう。
コインを取れるようになりました。
コインを取ったら一時停止をし、
インスペクターでコイン数を確認してみましょう。
←1.一時停止ボタン
←2.GameManagerを選択 ←3.コイン数を確認
©makohira2013
9.表示をつくる
取ったコイン数を画面に表示してみましょう。
GUIを使います。
今回は「GameManagerScript」に処理を書いてみます。
©makohira2013
1 using UnityEngine;
2 using System.Collections;
3
4 public class GameManagerScript : MonoBehaviour {
5
6 // パブリックなメンバ変数
7 public int Coins = 0; // 取ったコイン数を保持
8
9 // プライベートなメンバ変数
10 private Rect coinLabelRect = new Rect(10, 10, 400, 300);
11 private GUIStyle coinLabelStyle;
12
13 // Use this for initialization
14 void Start () {
15 coinLabelStyle = new GUIStyle();
16 coinLabelStyle.fontSize = 30;
17 coinLabelStyle.normal.textColor = Color.white;
18 }
19
20 // Update is called once per frame
21 void Update () {
22
23 }
24
25 // GUI
26 void OnGUI () {
27 GUI.Label(coinLabelRect, "Coins:" + Coins, coinLabelStyle);
28 }
29 }
「GameManagerScript.cs」にGUI表示を実装した例です。
←追加
©makohira2013
実行してみましょう。
コイン数が表示されるようになりました。
©makohira2013
今回はこれでおしまいですが、
余裕のある方は
背景をつけたり主人公や敵の絵を用意したりして
ゲームを完成してみてね。
©makohira2013
おしまい
お疲れ様でした。

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Unityで横スクロールアクションゲームを作ってみる(第2回unity初心者勉強会)