前提・実現したいこと
Unityはまだまだ始めたばかりで理解していない部分が多くあるので意味不明な質問内容があるかもしれませんが、どうかご指導お願いいたします。
https://miyagame.net/2d3d-samplegame/#i-2
こちらのページを参照し、サンプルゲームを作りました。
そして、これを自分でUnityを学びながら様々な機能を付けていこうと試み、まず移動の向きに応じてプレイヤーの向きを変更させようと考えました。
そこで参考にしたのがこのページです。>https://qiita.com/Eureka/items/01e9868588b507830889
該当のソースコード
C#で記述(Player_cotrollerのスクリプトです。)
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class PlayerController : MonoBehaviour 6{ 7 GameObject retryButton; 8 public AudioClip clip; 9 10 public float speed; //プレイヤーの動くスピード 11 12 private Vector3 Player_pos; //プレイヤーのポジション 13 private float x; 14 private float z; 15 private Rigidbody rigd; 16 17 // Start is called before the first frame update 18 void Start() 19 { 20 this.retryButton = GameObject.Find("RetryButton"); 21 retryButton.SetActive(false); 22 23 Player_pos = GetComponent<Transform>().position; //プレイヤーの初期位置を取得 24 rigd = GetComponent<Rigidbody>(); //プレイヤーのRigidbodyを取得 25 26 } 27 28 // Update is called once per frame 29 void Update() 30 { 31 32 x = Input.GetAxis("Horizontal"); //x方向のInputの値を取得 33 z = Input.GetAxis("Vertical"); //z方向のInputの値を取得 34 35 rigd.velocity = new Vector3(x * speed, 0, z * speed);//プレイヤーのRigidbodyに対してInputにspeedを掛けた値で更新し移動 36 37 Vector3 diff = transform.position - Player_pos; 38 39 if (diff.magnitude > 0.01f) 40 { 41 transform.rotation = Quaternion.LookRotation(diff); 42 } 43 44 Player_pos = transform.position; 45 46 } 47 48 // 右矢印ボタンを押したら移動するメソッド 49 public void RightArrowDown() 50 { 51 transform.Translate(2, 0, 0); 52 } 53 54 // 左矢印を押したら移動するメソッド 55 public void LeftArrowDown() 56 { 57 transform.Translate(-2, 0, 0); 58 } 59 60 //衝突した瞬間にオブジェクトを破壊 61 void OnTriggerEnter2D(Collider2D collision) 62 { 63 AudioSource.PlayClipAtPoint(clip, new Vector3(0, -3, 0)); 64 retryButton.SetActive(true); 65 Destroy(gameObject); 66 } 67} 68
試したこと
まずQiitaの使用例を丸写し
→rigdとspeedが移動に関する処理に使われていると判断したのでそれらが含まれる文章を削除してビルド
→→ディスプレイからプレイヤーが消える
移動の処理をする文章(rigd.velocity~)のみを削除
→動作はしたがプレイヤーの方向転換はできず
###質問したいこと
*speedがどこから取得されているのか(定義しているだけのように感じた)
*Rigidbodyを取得することに何の意味があるのか。
*どのようにすれば望んだ結果が得られるのか