UnityでOculus Touchを使うメモ ~銃を撃つ編~
かずまです。
昨日の記事ではOculus Touchでものを掴むところを実装しました。
今日は銃を扱うところを実装していきます。
銃の設定
今回はこのアセットをつかいました。
持つ部分にColliderを付けます。
ちなみにもモデルの方ではなくて、一つ上の親の方につけます。
Rigidbodyも付けます。
こんな感じ。
打った時の音も入れたいのでAudiosourceのコンポーネントも付けます。
ちなみにTouchを振動させる場合はAudioClipが必要みたいです。
最後にBulletPointという空のオブジェクトを子オブジェクトとして設定します。
位置は銃の先端にします。
Gun.csを作成
銃を撃つためのスクリプトを書いていきます。
このGun.csを先ほどColliderを付けた銃のモデルにつけます。
OVRInputはOculus Touchの右左によって違うので
if (holdHand.whichController == OVRInput.Controller.LTouch) { hapticsChannel = OVRHaptics.LeftChannel; whichFinger = OVRInput.RawButton.LIndexTrigger; } if (holdHand.whichController == OVRInput.Controller.RTouch) { hapticsChannel = OVRHaptics.RightChannel; whichFinger = OVRInput.RawButton.RIndexTrigger; }
昨日のコードでenumで設定したRTouchか、LTouchかをOVRHandからとってきます。
Triggerはものを持つ部分でつかいました。
今回銃を持ったのち、人差し指で発射します。
人差し指は
OVRInput.RawButton.RIndexTrigger
OVRInput.RawButton.LIndexTrigger
で取れます。
これを掴んだときにどっちの手でつかんだか、というのをgetHandメソッド内でやります。
弾痕を作る
gametukurikata.com
ここでは弾痕の実装を参考にします。
ありがたい。絵も提供されています。
Bullet.csをつくる
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public GameObject bullet_hit; // Use this for initialization void Start () { RaycastHit hit; if(Physics.Raycast(transform.position, transform.forward * 100f, out hit)) { GameObject obj = Instantiate (bullet_hit, hit.point - transform.root.forward * 0.001f, Quaternion.FromToRotation(Vector3.forward, hit.normal)); obj.transform.parent = hit.collider.transform; } } private void OnCollisionEnter (Collision col) { Destroy (this.gameObject); } // Update is called once per frame void Update () { GetComponent<Rigidbody> ().velocity = transform.forward * 10f; } }
Bulletオブジェクトをつくる
簡単な感じでそれっぽく作ります。
これにBullet.csをアタッチします。
たぶんこれでOKです。
ほとんどVR要素ないですが。笑