自動ドアの制御(1) Collision Detection
Unity勉強会用の資料として。
自動ドアの制御の3つのやり方、その1。
—————————————————
3つの衝突判定
・Collision Detection [detecting]:コライダーがぶつかっているかどうかで判定。
・Ray Casting [drawing]:コライダーがぶつかる前に、ベクターで対象を検知。
・Trigger Collision Detection [detecting]:コライダーの領域内にもう1つのコライダーが重なっているかどうかで判定。
—————————————————
Approach 1 : Collision detection
デモはこちら。
コライダーがぶつかっているかどうかで判定。
特徴:ドアに接触すると、ドアが開く。
欠点:ぶつからないとドアが開かない。
—————————————————
スクリプト ‘PlayerCollisions’ をプレイヤーに適用する。
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 41 42 43 44 45 46 47 48 49 50 51 52 53 |
using UnityEngine; using System.Collections; public class PlayerCollisions : MonoBehaviour { bool doorIsOpen = false; float doorTimer = 0.0f; GameObject currentDoor; public float doorOpenTime = 3.0f; public AudioClip doorOpenSound; public AudioClip doorShutSound; // Update is called once per frame. void Update () { // ドアが開いているかどうかを監視. if(doorIsOpen){ // ドアが開いている場合. doorTimer += Time.deltaTime; // フレーム間に経過している時間でタイマーをカウント. if(doorTimer > doorOpenTime){ // 一定時間を過ぎた場合. //ShutDoor(currentDoor); Door (doorShutSound, false, "doorshut", currentDoor); // ドアを閉める. doorTimer = 0.0f; // タイマーをリセットする. } } } void OnControllerColliderHit(ControllerColliderHit hit){ // 衝突を監視. if(hit.gameObject.tag == "playerDoor" && doorIsOpen == false){ // 衝突対象のタグ名が'playerDoor'で、かつドアが開いている場合. currentDoor = hit.gameObject; // ドアの GameObject の情報を変数に格納. //OpenDoor(currentDoor); Door (doorOpenSound, true, "dooropen", currentDoor); // Door (サウンドの指定、ドアが開いているか、再生するアニメーションの名前、衝突したドアの情報). } } /*void OpenDoor(GameObject door){ doorIsOpen = true; door.audio.PlayOneShot(doorOpenSound); door.transform.parent.animation.play("dooropen"); } void ShutDoor(GameObject door){ doorIsOpen = false; door.audio.PlayOneShot(doorShutSound); door.transform.parent.animation.play("doorshut"); }*/ void Door(AudioClip aClip, bool openCheck, string animName, GameObject thisDoor){ thisDoor.audio.PlayOneShot(aClip); // audio source を参照し、一度だけ音を鳴らす. doorIsOpen = openCheck; // ドアの状態を更新. thisDoor.transform.parent.animation.Play(animName); // 親の outPost に設定されているアニメーションを再生. } } |