Unityで女の子を前方のほうに走らせているのですが、車のPrefabにぶつかったら徐々に減速させて停止させたいです。
コードは以下のように記載して、女の子のキャラクターにアタッチしています。
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.UI; 5 6public class UnityChanController_2 : MonoBehaviour 7{ 8 //アニメーションするためのコンポーネントを入れる 9 private Animator myAnimator; 10 11 //Unityちゃんを移動させるコンポーネントを入れる 12 private Rigidbody myRigidbody; 13 14 private float forwardForce = 800.0f; 15 16 private float turnForce = 500.0f; 17 18 private float movableRange = 3.4f; 19 20 private float jumpForce = 500.0f; 21 22 private float coefficient = 0.95f; 23 24 private bool isEnd = false; 25 26 // Start is called before the first frame update 27 void Start() 28 { 29 //Animatorコンポーネントの取得 30 this.myAnimator = GetComponent< Animator > (); 31 32 //走るアニメーションを開始 33 this.myAnimator.SetFloat("Speed", 1); 34 35 //Rigitbobyコンポーネントの取得 36 this.myRigidbody = GetComponent<Rigidbody>(); 37 38 } 39 40 // Update is called once per frame 41 void Update() 42 { 43 if (this.isEnd) { 44 //Unityちゃんにかかっている力を落としている 45 this.forwardForce *= this.coefficient; 46 this.turnForce *= this.coefficient; 47 this.jumpForce *= this.coefficient; 48 this.myAnimator.speed *= this.coefficient; 49 } 50 51 52 53 //Unityちゃんに前方向の力を加える 54 //AddForce関数の引数(力の方向×力) 55 //transform.forward=ワールド空間の青軸(Z軸)方向、privateで定義した値(力)= forwardForce 56 this.myRigidbody.AddForce(this.transform.forward * this.forwardForce); 57 58 59 //Unityちゃんを矢印キーまたはボタンに応じて左右に移動させる(追加) 60 if (Input.GetKey("left") && -this.movableRange < this.transform.position.x) 61 { 62 //左に移動(追加) 63 this.myRigidbody.AddForce(-this.turnForce, 0, 0); 64 } 65 else if (Input.GetKey("right") && this.movableRange > this.transform.position.x ) 66 { 67 //右に移動(追加) 68 this.myRigidbody.AddForce(this.turnForce, 0, 0); 69 } 70 71 //Jumpステートの場合は、Jumpにfalseをセットする 72 if (this.myAnimator.GetCurrentAnimatorStateInfo(0).IsName("Jump")) 73 { 74 this.myAnimator.SetBool("Jump", false); 75 } 76 77 //ジャンプしていないときにスペースが押されたらジャンプする 78 if (Input.GetKeyDown(KeyCode.UpArrow) && this.transform.position.y < 0.5f) 79 { 80 //ジャンプアニメを再生 81 this.myAnimator.SetBool("Jump", true); 82 //Unityちゃんに上方向の力を加える 83 this.myRigidbody.AddForce(this.transform.up * this.jumpForce); 84 } 85 } 86 void OntriggerEnter(Collider other) 87 { 88 if(other.gameObject.tag == "CarTag" || other.gameObject.tag == "TrafficConeTag") 89 { 90 this.isEnd = true; 91 } 92 93 if(other.gameObject.tag == "GoalTag") 94 { 95 this.isEnd = true; 96 } 97 } 98}
なお、上の写真の中で、女の子とぶつかっている車のCarPrefabには、IstTrigerにチェック入れています。
何か足りない点がありましたら、教えていただけたらありがたいです。よろしくお願いいたします
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/18 08:33