自動ドアの制御(2) Ray casting
Unity勉強会用の資料として。
自動ドアの制御の3つのやり方、その2。
—————————————————
3つの衝突判定
・Collision Detection [detecting]:コライダーがぶつかっているかどうかで判定。
・Ray Casting [drawing]:コライダーがぶつかる前に、ベクターで対象を検知。
・Trigger Collision Detection [detecting]:コライダーの領域内にもう1つのコライダーが重なっているかどうかで判定。
—————————————————
Approach 2 : Ray casting
デモはこちら。
コライダーがぶつかる前に、ベクターで対象を検知。
特徴:一定の距離に近づき、ドアの方向を向くと、ドアが開く。
欠点:ドアの方向を向かないと開かない。
—————————————————
スクリプト ‘DoorManager’ をドアに適用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using UnityEngine; using System.Collections; public class DoorManager : MonoBehaviour { bool doorIsOpen = false; float doorTimer = 0.0f; public float doorOpenTime = 3.0f; public AudioClip doorOpenSound; public AudioClip doorShutSound; // Use this for initialization. void Start () { doorTimer = 0.0f; // タイマーをリセット. } // Update is called once per frame. void Update () { if(doorIsOpen){ // ドアが開いていた場合. doorTimer += Time.deltaTime; // タイマーを更新. if(doorTimer > doorOpenTime){ // 規定値に到達した場合. Door (doorShutSound, false, "doorshut"); // ドアを閉める. doorTimer = 0.0f; // タイマーをリセット. } } } void DoorCheck(){ if(!doorIsOpen){ // ドアが閉まっている場合. Door (doorOpenSound, true, "dooropen"); // ドアを開く. } } void Door(AudioClip aClip, bool openCheck, string animName){ // ここでは閉める場合にしか使用せず. audio.PlayOneShot(aClip); doorIsOpen = openCheck; transform.parent.gameObject.animation.Play(animName); } } |
—————————————————
スクリプト ‘PlayerCollisions’ をプレイヤーに適用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using UnityEngine; using System.Collections; public class PlayerCollisions : MonoBehaviour { GameObject currentDoor; // Update is called once per frame. void Update () { RaycastHit hit; // ray の情報を格納するための RaycastHit 型の変数 'hit' を用意. if(Physics.Raycast(transform.position, transform.forward, out hit, 3)){ // Raycast(プレイヤーの位置、ray の方向、ray の情報を格納する変数、ray の長さ). // 'out' を用いて 'hit' への参照を引数として渡す. if(hit.collider.gameObject.tag == "playerDoor"){ // 衝突対象のタグ名が 'playerDoor' だった場合. currentDoor = hit.collider.gameObject; // 衝突対象の GameObject を変数に格納. currentDoor.SendMessage("DoorCheck"); // 衝突対象の GameObject の関数 'DoorCheck' を呼び出す. } } } } |
C# の ‘out’ パラメータについて。
http://msdn.microsoft.com/en-us/library/ee332485.aspx
・参照渡し ⇔ 値渡し