シューティングチュートリアルをUnity5で(第03回まで)
Unity公式サイトのチュートリアルを行ってみました。全てできたのですが、Unity4用に書かれたチュートリアルなのでUnity5だと戸惑ったり書き換えが必要な箇所が結構あったのでまとめました。
このチュートリアルを始める前に
1.3 Unityを起動しよう
DLしたShootingGame.zipを解凍して開くと"Project Upgrade Required"のメッセージが出る。 →Upgradeボタンを押す
第01回
Texture Import Settings の確認
選択すべきTexture Typeは"Sprite"ではなく"Sprite (2D and UI)"となる。
第02回
スクリプトを書く
- Updateメソッドで使われているrigidbody2Dは クラス内で前もって宣言し、Startメソッド内で取得しておく。 スクリプトに関しては大概このようにコンポーネントにアクセスする際のお話でした。
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float speed = 5; private Rigidbody2D rb2; //宣言 void Start() { rb2 = GetComponent<Rigidbody2D>(); //取得 } // Update is called once per frame void Update () { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); Vector2 direction = new Vector2(x, y).normalized; rb2.velocity = direction * speed; //使用 } }
第03回
弾を動かす
Rigidbody2Dを前もって取得しておく。
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int speed = 10; private Rigidbody2D rb2; // Use this for initialization void Start () { rb2 = GetComponent<Rigidbody2D>(); rb2.velocity = transform.up * speed; } }
3.3 プレイヤーから弾を発射する
- Transformを前もって取得する。
- メソッド名"Start"は初期処理で使うのでコルーチン名は別の名前にする。
- コルーチンはStartメソッド内でStartCoroutineを明示的に呼ばないと実行されない。
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float speed = 5; public GameObject bullet; private Rigidbody2D rb2; private Transform tran; void Start() { rb2 = GetComponent<Rigidbody2D>(); StartCoroutine("IE"); } IEnumerator IE() { while (true) { tran = GetComponent<Transform>(); Instantiate(bullet, tran.position, tran.rotation); yield return new WaitForSeconds(0.05f); } } // Update is called once per frame void Update () { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); Vector2 direction = new Vector2(x, y).normalized; rb2.velocity = direction * speed; } }