※ これは 2021/03/12 時点の Unity 2020.3.0f1 の情報です
最新版では動作が異なる可能性がありますのでご注意ください
前回は下記のように2匹のねこキャラを NavMeshAgent
を使って Tilemap
にしたがって移動するようにした
今回はこの2匹の移動速度を変えて動かしてみたい
スポンサードリンク
といってもやるのは MainView.cs
の修正のみ
using UnityEngine; using UnityEngine.AI; using UnityEngine.InputSystem; public class MainView : MonoBehaviour { [SerializeField] private GameObject tapEffect = null; [SerializeField] private GameObject agentPrefab = null; [SerializeField] private Cat cat = null; [SerializeField] private Cat chaser = null; private NavMeshAgent catAgent = null; private NavMeshAgent chaserAgent = null; public void Start() { // NavMeshAgent を生成し、ねこキャラと連携させる this.catAgent = Instantiate(this.agentPrefab, this.cat.transform.position, Quaternion.identity, this.transform) .GetComponent<NavMeshAgent>(); this.chaserAgent = Instantiate(this.agentPrefab, this.chaser.transform.position, Quaternion.identity, this.transform) .GetComponent<NavMeshAgent>(); // 白ねこは速く this.catAgent.speed = 3.5f; this.catAgent.angularSpeed = 120f; this.catAgent.acceleration = 8f; // トラねこは遅く this.chaserAgent.speed = 2f; this.chaserAgent.angularSpeed = 60f; this.chaserAgent.acceleration = 4f; this.cat.Agent = this.catAgent; this.chaser.Agent = this.chaserAgent; } public void Update() { // ねこキャラを追いかけさせる this.chaser.Agent.SetDestination(this.cat.transform.position); } public void OnFire(InputAction.CallbackContext context) { var target = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue()); this.cat.Agent.SetDestination(target); // タップ跡を表示 var effect = Instantiate(this.tapEffect, (Vector2)target, Quaternion.identity, this.transform); // 1秒後に消滅 Destroy(effect, 1f); } }
NavMeshAgent.speed
は最高速度 (unit/s)、NavMeshAgent.angularSpeed
は最高回転速度 (degree/s)、NavMeshAgent.acceleration
は加速度 (unit/s2) らしい
適当にトラねこを遅くして動かしてみると
かんたんにできた!