質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Unity3D

Unity3Dは、ゲームや対話式の3Dアプリケーション、トレーニングシュミレーション、そして医学的・建築学的な技術を可視化する、商業用の開発プラットフォームです。

Q&A

解決済

1回答

2826閲覧

UnityでJoystickを使用したキャラ移動を実現したい

shibi

総合スコア4

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Unity3D

Unity3Dは、ゲームや対話式の3Dアプリケーション、トレーニングシュミレーション、そして医学的・建築学的な技術を可視化する、商業用の開発プラットフォームです。

0グッド

0クリップ

投稿2019/11/26 07:01

前提・実現したいこと

unity、プログラミングともに初心者です。
また、このようにサイトを通じて質問をすることも初めてのため、ご質問するにあたって情報が不足していたり
至らない点があれば教えていただけますと幸いです。

Unityで3Dのゲームを製作中で、プラットフォームをスマホ・タブレットにするため
キャラの移動をジョイスティックを使ったものにしようと考えていたのですが、
ジョイスティックとキャラの動きをうまく関連づけられずに困っています。
使用しているUnityのバージョンは2019.1.10f1で、SDキャラのユニティちゃんを動かしています。

UnityStandardAssets > CrossPlatformInput > Scriptsフォルダの中にあるJoystickスクリプトを用いて作った
Joystickからpositionの情報を、UnityStandardAssets > ThirdPersonCharacter > Scriptsフォルダの中にある
ThirdPersonUserControlスクリプト内に新しく作ったinputHorizontal、Verticalの代わりになる変数に
入れようとしているのですがうまくいきません。

デフォルト状態からのスクリプトの変更点

この後該当のスクリプトを貼るのですが、それを見ていただく前にデフォルトからの変更箇所を
先にお伝えした方が良いのではないかと考え、これを書いています。
もしスクリプトを全部読んだ上で判断する前提だから必要ない、という場合はこの次の『該当のソースコード』の欄から
ご覧いただけますと幸いです。

一つ目のThirdPersonUseControlは、デフォルトのものに対して上から15~16行目の

public float inputY; public float inputX;

を追加したことと、51〜54行目の

// float h = CrossPlatformInputManager.GetAxis("Horizontal"); ジョイコンのために消した二行↓ // float v = CrossPlatformInputManager.GetAxis("Vertical"); ここから下の二行はそのために追加したもの float h = inputY; float v = inputX;

51,52をコメントアウトして
53,54を新しく追加した点が変更を加えた箇所です。

次にJoystickの変更点は
上から21行目の

public GameObject posController; //位置をコントロールする対象のオブジェクトを指定

という、ThirdPersonUseControlを適応したゲームオブジェクトを参照するために一行スクリプトを用意したものと
120〜121行目の

posController.GetComponent<ThirdPersonUserControl>().inputX = position.x; posController.GetComponent<ThirdPersonUserControl>().inputY = position.y;

Joystickのpositionの数値をThirdPersonUseControl内のinputX,Yに
受け渡す目的で追加した2行が入っている箇所が変更点です。

該当のソースコード

ThirdPersonUseControl

C#

1using System; 2using UnityEngine; 3using UnityStandardAssets.CrossPlatformInput; 4 5namespace UnityStandardAssets.Characters.ThirdPerson 6{ 7 [RequireComponent(typeof (ThirdPersonCharacter))] 8 public class ThirdPersonUserControl : MonoBehaviour 9 { 10 private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object 11 private Transform m_Cam; // A reference to the main camera in the scenes transform 12 private Vector3 m_CamForward; // The current forward direction of the camera 13 private Vector3 m_Move; 14 private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input. 15 public float inputY; 16 public float inputX; 17 18 19 private void Start() 20 { 21 // get the transform of the main camera 22 if (Camera.main != null) 23 { 24 m_Cam = Camera.main.transform; 25 } 26 else 27 { 28 Debug.LogWarning( 29 "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject); 30 // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them! 31 } 32 33 // get the third person character ( this should never be null due to require component ) 34 m_Character = GetComponent<ThirdPersonCharacter>(); 35 } 36 37 38 private void Update() 39 { 40 if (!m_Jump) 41 { 42 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); 43 } 44 } 45 46 47 // Fixed update is called in sync with physics 48 private void FixedUpdate() 49 { 50 // read inputs 51 // float h = CrossPlatformInputManager.GetAxis("Horizontal"); ジョイコンのために消した二行↓ 52 // float v = CrossPlatformInputManager.GetAxis("Vertical"); ここから下の二行はそのために追加したもの 53 float h = inputY; 54 float v = inputX; 55 bool crouch = Input.GetKey(KeyCode.C); 56 57 // calculate move direction to pass to character 58 if (m_Cam != null) 59 { 60 // calculate camera relative direction to move: 61 m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized; 62 m_Move = v*m_CamForward + h*m_Cam.right; 63 } 64 else 65 { 66 // we use world-relative directions in the case of no main camera 67 m_Move = v*Vector3.forward + h*Vector3.right; 68 } 69#if !MOBILE_INPUT 70 // walk speed multiplier 71 if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f; 72#endif 73 74 // pass all parameters to the character control script 75 m_Character.Move(m_Move, crouch, m_Jump); 76 m_Jump = false; 77 } 78 } 79} 80
Joystick

C#

1using System; 2using UnityEngine; 3using UnityEngine.EventSystems; 4 5namespace UnityStandardAssets.CrossPlatformInput 6{ 7 public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler 8 { 9 public enum AxisOption 10 { 11 // Options for which axes to use 12 Both, // Use both 13 OnlyHorizontal, // Only horizontal 14 OnlyVertical // Only vertical 15 } 16 17 public int MovementRange = 100; 18 public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use 19 public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input 20 public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input 21 public GameObject posController; //位置をコントロールする対象のオブジェクトを指定 22 23 Vector3 m_StartPos; 24 bool m_UseX; // Toggle for using the x axis 25 bool m_UseY; // Toggle for using the Y axis 26 CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input 27 CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input 28 29 void OnEnable() 30 { 31 CreateVirtualAxes(); 32 } 33 34 void Start() 35 { 36 m_StartPos = transform.position; 37 } 38 39 void UpdateVirtualAxes(Vector3 value) 40 { 41 var delta = m_StartPos - value; 42 delta.y = -delta.y; 43 delta /= MovementRange; 44 if (m_UseX) 45 { 46 m_HorizontalVirtualAxis.Update(-delta.x); 47 } 48 49 if (m_UseY) 50 { 51 m_VerticalVirtualAxis.Update(delta.y); 52 } 53 } 54 55 void CreateVirtualAxes() 56 { 57 // set axes to use 58 m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); 59 m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); 60 61 // create new axes based on axes to use 62 if (m_UseX) 63 { 64 m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName); 65 CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); 66 } 67 if (m_UseY) 68 { 69 m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); 70 CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); 71 } 72 } 73 74 75 public void OnDrag(PointerEventData data) 76 { 77 Vector3 newPos = Vector3.zero; 78 79 if (m_UseX) 80 { 81 int delta = (int)(data.position.x - m_StartPos.x); 82 delta = Mathf.Clamp(delta, - MovementRange, MovementRange); 83 newPos.x = delta; 84 } 85 86 if (m_UseY) 87 { 88 int delta = (int)(data.position.y - m_StartPos.y); 89 delta = Mathf.Clamp(delta, -MovementRange, MovementRange); 90 newPos.y = delta; 91 } 92 transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z); 93 UpdateVirtualAxes(transform.position); 94 } 95 96 97 public void OnPointerUp(PointerEventData data) 98 { 99 transform.position = m_StartPos; 100 UpdateVirtualAxes(m_StartPos); 101 } 102 103 104 public void OnPointerDown(PointerEventData data) { } 105 106 void OnDisable() 107 { 108 // remove the joysticks from the cross platform input 109 if (m_UseX) 110 { 111 m_HorizontalVirtualAxis.Remove(); 112 } 113 if (m_UseY) 114 { 115 m_VerticalVirtualAxis.Remove(); 116 } 117 } 118 } 119 //float posController = GameObject.FindObjectOfType(ThirdPersonController) as ThirdPersonController; 120 posController.GetComponent<ThirdPersonUserControl>().inputX = position.x; 121 posController.GetComponent<ThirdPersonUserControl>().inputY = position.y; 122}

試したこと

これを作るにあたって参考にしたサイトのURLをここに貼ろうと思います。

一番参考にしたサイト
UnityでJoystick(ジョイスティック)を追加する方法【初心者向け】

別オブジェクトを参照する方法を参考にしたサイト
Unity-他のスクリプトを触る

その他、参考にしたサイト(反映度合:低)
Unityちゃんをジョイスティックで動かす方法【スマホ対応】
【Unity】スクリプトを他のスクリプトから参照する方法

いろんなサイト(ジョイスティック系)を見ている中で、自分の使っているスタンダードアセットとは異なる物を記事の方々は使っているのではないかと思いました。
ただ、自分が使っているそれのバージョンがなんなのかを確認する方法がわからず、ここに情報として載せることはできません。
申し訳ありません。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

なんとか自己解決(人に相談して)できました。

問題があったのはJoystickスクリプトの方だったようです。
頭の方で、本来using UnityStandardAssets.Characters.ThirdPersonを宣言しなければいけないところ、それをしていなかった、というのが大きな理由でした。

その他、元のJoystickスクリプトの下から二行目あたりに記述してた以下のコードを、修正後のスクリプトでは、UpdateVirtualAxesクラス内に書き換えています。

posController.GetComponent<ThirdPersonUserControl>().inputX = position.x; posController.GetComponent<ThirdPersonUserControl>().inputY = position.y;

修正後のソースコード

Joystick

C#

1using System; 2using UnityEngine; 3using UnityEngine.EventSystems; 4using UnityStandardAssets.Characters.ThirdPerson; 5 6namespace UnityStandardAssets.CrossPlatformInput 7{ 8 public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler 9 { 10 public enum AxisOption 11 { 12 // Options for which axes to use 13 Both, // Use both 14 OnlyHorizontal, // Only horizontal 15 OnlyVertical // Only vertical 16 } 17 18 public int MovementRange = 100; 19 public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use 20 public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input 21 public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input 22 public GameObject posController; //キャラ位置をコントロールする対象のオブジェクトを指定 23 public GameObject camController; //カメラ位置をコントロールする対象のオブジェクトを指定 24 25 Vector3 m_StartPos; 26 bool m_UseX; // Toggle for using the x axis 27 bool m_UseY; // Toggle for using the Y axis 28 CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input 29 CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input 30 31 void OnEnable() 32 { 33 CreateVirtualAxes(); 34 } 35 36 void Start() 37 { 38 m_StartPos = transform.position; 39 } 40 41 void UpdateVirtualAxes(Vector3 value) 42 { 43 var delta = m_StartPos - value; 44 delta.y = -delta.y; 45 delta /= MovementRange; 46 if (m_UseX) 47 { 48 m_HorizontalVirtualAxis.Update(delta.x); 49 posController.GetComponent<ThirdPersonUserControl>().inputX = delta.x; 50 } 51 52 if (m_UseY) 53 { 54 m_VerticalVirtualAxis.Update(delta.y); 55 posController.GetComponent<ThirdPersonUserControl>().inputX = delta.y; 56 } 57 } 58 59 void CreateVirtualAxes() 60 { 61 // set axes to use 62 m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); 63 m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); 64 65 // create new axes based on axes to use 66 if (m_UseX) 67 { 68 m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName); 69 CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); 70 } 71 if (m_UseY) 72 { 73 m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); 74 CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); 75 } 76 } 77 78 79 public void OnDrag(PointerEventData data) 80 { 81 Vector3 newPos = Vector3.zero; 82 83 if (m_UseX) 84 { 85 int delta = (int)(data.position.x - m_StartPos.x); 86 delta = Mathf.Clamp(delta, -MovementRange, MovementRange); 87 newPos.x = delta; 88 } 89 90 if (m_UseY) 91 { 92 int delta = (int)(data.position.y - m_StartPos.y); 93 delta = Mathf.Clamp(delta, -MovementRange, MovementRange); 94 newPos.y = delta; 95 } 96 transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z); 97 UpdateVirtualAxes(transform.position); 98 } 99 100 101 public void OnPointerUp(PointerEventData data) 102 { 103 transform.position = m_StartPos; 104 UpdateVirtualAxes(m_StartPos); 105 } 106 107 108 public void OnPointerDown(PointerEventData data) { } 109 110 void OnDisable() 111 { 112 // remove the joysticks from the cross platform input 113 if (m_UseX) 114 { 115 m_HorizontalVirtualAxis.Remove(); 116 } 117 if (m_UseY) 118 { 119 m_VerticalVirtualAxis.Remove(); 120 } 121 } 122 //float posController = GameObject.FindObjectOfType(ThirdPersonController) as ThirdPersonController; 123 //posController.GetComponent<ThirdPersonUserControl>().inputX = position.x; 124 //posController.GetComponent<ThirdPersonUserControl>().inputY = position.y; 125 } 126}

投稿2019/11/27 11:17

shibi

総合スコア4

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問