Unityの制作本に沿ってやっていたところ、少し疑問だったので質問させていただきます。
画面を押してから離すまでの距離の長さに応じて車が動くという簡単なゲームのスクリプトを書いているのですが
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class CarController : MonoBehaviour { 6 float speed = 0; 7 Vector2 startPos; 8 9 10 // Use this for initialization 11 void Start () { 12 13 } 14 15 // Update is called once per frame 16 void Update () { 17 if (Input.GetMouseButtonDown(0)) 18 { 19 //マウスをクリックした座標 20 this.startPos = Input.mousePosition; 21 } 22 else if(Input.GetMouseButtonUp(0)){ 23 //マウスを離した座標 24 Vector2 endPos = Input.mousePosition; 25 float swipeLength = (endPos.x - this.startPos.x); 26 27 //スワイプの長さを初速度に変換 28 this.speed = swipeLength / 500.0f; 29 } 30 31 transform.Translate(this.speed, 0, 0); 32 this.speed *= 0.98f; 33 34 } 35} 36
上記が正しいコードとのことなのですが
次のように表記しては何故ダメなのでしょうか
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class CarController : MonoBehaviour { 6 float speed = 0; 7 8 9 // Use this for initialization 10 void Start () { 11 12 } 13 14 // Update is called once per frame 15 void Update () { 16 if (Input.GetMouseButtonDown(0)) 17 { 18 //マウスをクリックした座標 19 Vector2 startPos = Input.mousePosition; 20 } 21 else if(Input.GetMouseButtonUp(0)){ 22 //マウスを離した座標 23 Vector2 endPos = Input.mousePosition; 24 float swipeLength = (this.endPos.x - this.startPos.x); 25 26 //スワイプの長さを初速度に変換 27 this.speed = swipeLength / 500.0f; 28 } 29 30 31 32 transform.Translate(this.speed, 0, 0); 33 this.speed *= 0.98f; 34 35 } 36} 37
疑問点としては
・Vector2 startPos;は最初に表記しているのにendPosは何故宣言しないのか。
・float swipeLength = (endPos.x - this.startPos.x);
の部分でendPosにthis.をつけないのはなぜか。
・後者のコードのように書くとなぜエラーになるのか
初心者のため情報に不足があったり、的外れな質問でしたら申し訳ないです。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/28 08:43