前提
Unity初心者です。
現在Unityでアクションゲームを作ろうとしています。
実現したいこと
カメラにが向いている方向(写っている画面の方向)を進行方向(z方向)としてキャラクターを動かしたいのですが、やり方がわかりません。
(ワールドの絶対的な前後左右にむかって移動するのではなく、カメラの向きや位置によってその時の前後左右が変わるようにしたいです。3Dマリオのようなイメージです。)
また、プレイヤーはキャラクターコントローラーを使って移動させたいと考えています。
現状カメラはプレイヤーを中心に回転し、追従するようにしています。
ソースコードを貼っておきます。
カメラの制御スクリプト自体はおそらく間違っていないと思うのですが、プレイヤーの移動のスクリプトをどう組めば、カメラに写っている方向を進行方向として移動できるのかがわかりません。
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class Camerafollow : MonoBehaviour 6{ 7 public GameObject target; 8 Vector3 targetPosi; 9 10 11 float angle; 12 public float RotateSpeed; 13 14 15 16 // Start is called before the first frame update 17 void Start() 18 { 19 targetPosi=target.transform.position; 20 } 21 22 private void Update() 23 { 24 //追従処理 25 transform.position += target.transform.position-targetPosi; 26 targetPosi =target.transform.position; 27 28 //回転処理 29 angle = Input.GetAxis("Horizontal2") * RotateSpeed; 30//Horizontal2はPS4コントローラーの右スティックの入力に対応させています。 31 32 transform.RotateAround(targetPosi, Vector3.up, angle); 33 }
試したこと
以下の移動スクリプトを書いたのですがうまく動かないという状況です。
おそらくこの移動に関して間違いがあると思うのですが、どこがどう間違えているかわからないという状況です。
C#
1public class PlayerMove : MonoBehaviour 2{ 3 4 [SerializeField] private float moveSpeed = 3; 5 6 private CharacterController _characterController; 7 8 public Vector3 _moveVelocity; 9 10 [SerializeField] private GameObject Camera; 11 12 float inputHorizontal; 13 float inputVertical; 14 15 16 void Start() 17 { 18 _characterController = GetComponent<CharacterController>(); 19 20 } 21 22 void Update() 23 { 24 if (_characterController.isGrounded) 25 { 26 27 //入力された方向にスピードをかける 28 inputHorizontal = Input.GetAxis("Horizontal") * moveSpeed; 29 inputVertical = Input.GetAxis("Vertical") * moveSpeed; 30 31 32 //カメラの向きをもったベクトルに上で算出されたものをかける 33 _moveVelocity = Camera.transform.forward * inputVertical + Camera.transform.right * inputHorizontal; 34 35 36 37 //入力された方向に向く 38 _transform.LookAt(_transform.position + new Vector3(_moveVelocity.x, 0, _moveVelocity.z)); 39 40 41 42 43 _characterController.Move(_moveVelocity * Time.deltaTime); 44 45 } 46}
回答1件
あなたの回答
tips
プレビュー