ナビメッシュで巡回中に停止させてアニメーションさせる

投稿者: | 2020-04-01


ナビメッシュエージェントに巡回させて、目的地に付いた時に一旦巡回を停止させて、その場でアニメーションさせてみました。

NPCにスクリプトを付けて、ベンチと2つの目的地をアタッチしています。

目的地は空のゲームオブジェクトで、少し離れたところと、ベンチの前に置きます。

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.AI;
  5.  
  6. public class AgentScript : MonoBehaviour
  7. {
  8. public Transform[] point;
  9. public Transform bench;
  10. NavMeshAgent agent;
  11. Animator animator;
  12.  
  13. int n = 0;
  14.  
  15. // Start is called before the first frame update
  16. void Start()
  17. {
  18. agent = GetComponent<NavMeshAgent>();
  19. animator = GetComponent<Animator>();
  20.  
  21. agent.destination = point[0].position;
  22. }
  23.  
  24. // Update is called once per frame
  25. void Update()
  26. {
  27. // 目的地に近づいたら
  28. if (!agent.pathPending && agent.remainingDistance < 0.5f)
  29. {
  30.  
  31. if (n == 0) n = 1;
  32. else n = 0;
  33.  
  34.  
  35. // ベンチの前に来たとき
  36. if (n == 0)
  37. {
  38. agent.speed = 0f; // エージェントの動きを止める
  39. animator.SetInteger("param1",1); // 座るアニメーションに遷移させる
  40. agent.updateRotation = false; // 回転を止める
  41.  
  42. // ベンチにまっすぐ座るために回転させる
  43. Quaternion q = Quaternion.FromToRotation(transform.forward, bench.forward);
  44. transform.Rotate(q.eulerAngles);
  45.  
  46. agent.Warp(point[1].position); // ベンチの前にワープ
  47.  
  48. }
  49.  
  50.  
  51. agent.destination = point[n].position;
  52.  
  53. }
  54.  
  55.  
  56. if (animator.GetAnimatorTransitionInfo(0).IsName("Sitdown -> Walk"))
  57. {
  58. animator.SetInteger("param1", 0);
  59. agent.updateRotation = true; // 回転を再開
  60. agent.speed = 5f;
  61.  
  62. }
  63.  
  64. }
  65.  
  66. }

デフォルトが歩くアニメーションで、Int型のparam1が1になると、座るアニメーションに遷移します。

座るアニメーションが終わると自動的に歩くアニメーションに戻ります。

エージェントがベンチの前に来ると、speedを0にしてエージェントの動きを止めます。そのままではエージェントは座るアニメーションをしたまま目的地の方を向いてしまうので、agent.updateRotation = false; でエージェントの回転を止めています。

座る位置がずれないように、目的地の上にワープさせています。

NPCをベンチにまっすぐ座らせる



FromToRotationメソッドを使うと、第一引数の方向から第二引数の方向へ向かせるための回転値が得られます。

  1. Quaternion q = Quaternion.FromToRotation(transform.forward, bench.forward);
エージェントの正面の方向とベンチの正面の方向を入れています。

この回転をエージェントに加えます。
  1. transform.Rotate(q.eulerAngles);

アニメーターの遷移中の処理<

アニメーターのGetAnimatorTransitionInfoを使って遷移中の処理を書きます。

  1. if (animator.GetAnimatorTransitionInfo(0).IsName("Sitdown -> Walk"))
  2. {
  3. animator.SetInteger("param1", 0); // パラメーターを0に戻す
  4. agent.updateRotation = true; // 回転を再開
  5. agent.speed = 5f;
  6. }

遷移の矢印のインスペクタで、「Transition Duration」が0になっているとGetAnimatorTransitionInfoは実行されないので、ここには0より大きい値を入れておきます。

コメントを残す

メールアドレスが公開されることはありません。