kazumalab tech log

流行りとリラックマと嵐が大好きです。技術的ログ。

UnityでOculus Touchを使うメモ ~銃を撃つ編~

かずまです。

昨日の記事ではOculus Touchでものを掴むところを実装しました。

blog.kazumalab.com

今日は銃を扱うところを実装していきます。

銃の設定

www.asset.techmatome.com

今回はこのアセットをつかいました。


f:id:kazumalab:20170217231856p:plain

持つ部分にColliderを付けます。
ちなみにもモデルの方ではなくて、一つ上の親の方につけます。

Rigidbodyも付けます。

f:id:kazumalab:20170217232337p:plain

こんな感じ。
打った時の音も入れたいのでAudiosourceのコンポーネントも付けます。
ちなみにTouchを振動させる場合はAudioClipが必要みたいです。


f:id:kazumalab:20170217233021p:plain

最後に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オブジェクトをつくる

f:id:kazumalab:20170217234650p:plain

簡単な感じでそれっぽく作ります。
これにBullet.csをアタッチします。

たぶんこれでOKです。
ほとんどVR要素ないですが。笑

デモ

できました。