シューティングチュートリアルをUnity5で(第05回)
5.1 プレイヤーに当たり判定を付ける
- 指定の0.02だと衝突判定を起こせないのでSizeをX,Yともに0.05にする(冒頭の注意書きがこれ。全回に書いてあるので最初気づかなかった)。
5.2 エネミーに当たり判定を付ける
- コライダー編集を行う時はEdit Colliderボタンを押下する。ボタン色が濃灰になると編集モード。
スクリプトでレイヤー制御
- 特記事項なし
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { Spaceship spaceship; private Transform tran; void Start() { spaceship = GetComponent<Spaceship>(); tran = GetComponent<Transform>(); StartCoroutine("IE"); } IEnumerator IE() { while (true) { spaceship.Shot(tran); yield return new WaitForSeconds(spaceship.shotDelay); } } void Update () { float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); Vector2 direction = new Vector2(x, y).normalized; spaceship.Move(direction); } void OnTriggerEnter2D(Collider2D c) { string layerName = LayerMask.LayerToName(c.gameObject.layer); if (layerName == "Bullet(Enemy)") { Destroy (c.gameObject); } if (layerName == "Bullet(Enemy)" || layerName == "Enemy") { spaceship.Explosion (); Destroy (gameObject); } } }
エネミーの当たり判定
- 特記事項なし
using UnityEngine; using System.Collections; public class Enemy : MonoBehaviour { Spaceship spaceship; private Transform tran; void Start () { spaceship = GetComponent<Spaceship> (); tran = GetComponent<Transform> (); spaceship.Move (tran.up * -1); StartCoroutine ("IE"); } IEnumerator IE() { if (spaceship.canShot == false) { yield break; } while (true) { for (int i = 0; i < tran.childCount; i++) { Transform shotPosition = transform.GetChild (i); spaceship.Shot (shotPosition); } yield return new WaitForSeconds (spaceship.shotDelay); } } void OnTriggerEnter2D(Collider2D c) { string layerName = LayerMask.LayerToName (c.gameObject.layer); if (layerName != "Bullet(Player)") return; Destroy (c.gameObject); spaceship.Explosion (); Destroy (gameObject); } }
5.8 PlayerBulletゲームオブジェクトの削除
- 特記事項なし
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { public int speed = 10; public float lifeTime = 5; private Rigidbody2D rb2; void Start () { rb2 = GetComponent<Rigidbody2D>(); rb2.velocity = transform.up * speed; Destroy (gameObject, lifeTime); } }