前提
unityを使い始めて2か月の初心者です。
現在、車の運転シミュレーターゲーム(3D)を作成中です。
運転シミュレーターと言ってもドリフトやハンドル操作はなく、アクセルとブレーキの機能だけ付けたいと考えております。
(電車シミュレーターの方が完成イメージに近いです)
実現したいこと
・キーボードで加速減速の操作をできるようにしたい
発生している問題・エラーメッセージ
様々なサイトを参考に、車をコースに沿って走らせることはできたのですが、
キーボードで加速減速の操作をすることができません。
(再生すると勝手に道に沿って走り出します)
コードが間違っているのでしょうか?それとも車側に何か他の設定が必要でしょうか?
もしくは全く違うアプローチをした方が良いのでしょうか?
ご教授いただけますと幸いです。
よろしくお願いいたします。
エラーメッセージはありません
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine.AI; 4using UnityEngine; 5 6public class moveCarCon : MonoBehaviour 7{ 8 public Transform[] points; 9 private int destPoint = 0; 10 private NavMeshAgent agent; 11 12 // Start is called before the first frame update 13 void Start() 14 { 15 agent = GetComponent<NavMeshAgent>(); 16 17 // autoBraking を無効にすると、目標地点の間を継続的に移動します 18 //(つまり、エージェントは目標地点に近づいても 19 // 速度をおとしません) 20 agent.autoBraking = false; 21 22 GotoNextPoint(); 23 } 24 25 void GotoNextPoint() 26 { 27 // エージェントが現在設定された目標地点に行くように設定します 28 agent.destination = points[destPoint].position; 29 30 // 配列内の次の位置を目標地点に設定し、 31 // 必要ならば出発地点にもどります 32 destPoint = (destPoint + 1) % points.Length; 33 } 34 35 void Update() 36 { 37 if (Input.GetKey(KeyCode.UpArrow)) 38 { 39 agent.speed += 1f; 40 } 41 if (Input.GetKey(KeyCode.DownArrow)) 42 { 43 agent.speed -= 1f; 44 } 45 46 47 // エージェントが現目標地点に近づいてきたら、 48 // 次の目標地点を選択します 49 if (!agent.pathPending && agent.remainingDistance < 0.5f) 50 GotoNextPoint(); 51 } 52 53}
試したこと
下記のコードでも車を走らせてみましたが、移動時間の変え方?が分からず、こちらでもキー操作できませんでした。(再生すると勝手に道に沿って走り出します)
C#
1using System.Collections; 2using System.Collections.Generic; 3using DG.Tweening; 4using System.Linq; 5using UnityEngine; 6 7public class waypath : MonoBehaviour 8{ 9 [SerializeField] 10 private List<GameObject> _targets; 11 12 void FixedUpdate() 13 { 14 Rigidbody rb = this.GetComponent<Rigidbody>(); // rigidbodyを取得 15 Vector3 force = new Vector3(0.0f, 0.0f, 0.0f); // 力を設定 16 if (Input.GetKey(KeyCode.UpArrow)) 17 force.z += 0.5f; 18 if (Input.GetKey(KeyCode.Space)) 19 force.z -= 0.5f; 20 rb.AddForce(force, ForceMode.Force); // 力を加える 21 } 22 23 // Start is called before the first frame update 24 void Start() 25 { 26 27 transform.DOPath( 28 path: _targets.Select(target => target.transform.position).ToArray(), //移動する座標をオブジェクトから抽出 29 duration: 10f, //移動時間 30 pathType: PathType.CatmullRom//移動するパスの種類 31) 32 .SetLookAt(0.05f, Vector3.forward); 33 34 } 35 36 // Update is called once per frame 37 void Update() 38 { 39 40 } 41} 42 43
補足情報(FW/ツールのバージョンなど)
unityのバージョン…2021.3.15f1

回答1件
あなたの回答
tips
プレビュー