ハイサイ!プロトデータセンター新卒のIREIです。
引き続きUnityでGear VR用のアプリ開発事例を紹介していきます。
今回はシューティングです。
以下のコードを作成し、銃口となるオブジェクトに追加します。
using UnityEngine; using System.Collections; public class RayShot : MonoBehaviour { public float shotSpan = .1f; // 射程 public float shotRange = 100; // ヒットした時に与えるダメージ量 public int damage = 1; // 銃口 public Transform muzzle; private Camera camera; private LineRenderer lineRenderer; private WaitForSeconds shotLength = new WaitForSeconds(.03f); private AudioSource source; private float nextShotTime; void Awake() { lineRenderer = GetComponent<LineRenderer> (); source = GetComponent<AudioSource> (); camera = GetComponentInParent<Camera> (); } // Update is called once per frame void Update () { RaycastHit hit; Vector3 shotRayOrigin = camera.ViewportToWorldPoint (new Vector3 (.5f, .5f, 0)); // コントローラで発射ボタンを押した時 if (Input.GetButtonDown("Fire1") && Time.time > nextShotTime) { nextShotTime = Time.time + shotSpan; if (Physics.Raycast(shotRayOrigin, camera.transform.forward, out hit, shotRange)) { IDamageable dmgScript = hit.collider.gameObject.GetComponent<IDamageable>(); if (dmgScript != null) { dmgScript.Damage(damage, hit.point); } if(hit.rigidbody != null) { hit.rigidbody.AddForce(-hit.normal * 150f); } lineRenderer.SetPosition(0, muzzle.position); lineRenderer.SetPosition(1, hit.point); } StartCoroutine (GunEffect ()); } } private IEnumerator GunEffect() { source.Play (); lineRenderer.enabled = true; yield return shotLength; lineRenderer.enabled = false; } }
私の環境でコードを追加した先のオブジェクトはGunとなります。
追加するとMuzzleの項目が表示されます。
その項目にHierarcyにある銃口を示すMuzzleオブジェクトをドラッグ&ドロップで追加。
追加後、BLEコントローラで発射ボタンをおすと赤いレーザーが発射されます。
今度は敵にダメージを与えて倒しましょう!
using UnityEngine; public interface IDamageable { void Damage(int damage, Vector3 hitPoint); }
上記のIDamageable.csを作成後、
以下のEnemyHealth.csを作成します。
using UnityEngine; using System.Collections; public class EnemyHealth : MonoBehaviour, IDamageable { public int startingHealth = 4; private int currentHealth; void Start() { currentHealth = startingHealth; } public void Damage(int damage, Vector3 hitPoint) { currentHealth -= damage; if (currentHealth <= 0) { Defeated(); } } void Defeated() { gameObject.SetActive (false); } }
EnemyHealth.csの作成が完了したら、このスクリプトを敵であるMazeCharacterにドラッグ&ドロップで追加。
追加が完了後’、敵に一定以上のダメージを与えると消滅するようになりました!
なお、今回のデモを作成するにあたってUnityさんのチュートリアルを参考にさせて頂きました。
unity3d.com
他にも様々なチュートリアルがありますので是非チェックしてみてください!
VR最高!!