前提・実現したいこと
unity2017.4.0f1でミニゲームを制作しています。
ピンボールのようなゲームを作ろうと思い、ボールを飛ばそうとしています。
最初に、マウスのボタンを押したときの位置と離したときの距離などでボールにForceを与えました。
その時は、ボールは思ったように動いてくれました。
次に、クリックごとにボールを自動生成したいと思い、ボールのプレハブを作りました。
発生している問題・エラーメッセージ
そうしたら、マウスをクリックしたときの位置を上手く認識してくれません。
エラーメッセージ
該当のソースコード
unity
1//ボール制御のスクリプト 2using System.Collections; 3using System.Collections.Generic; 4using UnityEngine; 5 6public class BallController : MonoBehaviour { 7 Rigidbody2D rigid2D; 8 9 public Vector2 startPos; 10 public float scaleChange = 1.0f; 11 public int scaleSwitch = 1; 12 public float gravityChange = 2.0f; 13 public int gravitySwitch = 1; 14 public bool detectLaunch = false; 15 16 void Start () { 17 this.rigid2D = GetComponent<Rigidbody2D>(); 18 } 19 20 void Update () { 21 22 if(transform.position.y < -5.3f) { 23 Destroy(gameObject); 24 } 25 if(detectLaunch == true) { 26 this.rigid2D.AddForce(transform.up * - gravityChange); 27 }else{ 28 //クリックしたとき 29 if (Input.GetMouseButtonDown(0)) { 30 this.startPos = Input.mousePosition; 31 32 //離したとき 33 } else if(Input.GetMouseButtonUp(0)){ 34 Vector2 endPos = Input.mousePosition; 35 float distance = Vector2.Distance(this.startPos, endPos); 36 float distanceH = this.startPos.x - endPos.x; 37 this.rigid2D.AddForce(transform.up * distance); 38 this.rigid2D.AddForce(transform.right * distanceH); 39 Debug.Log(distanceH); 40 detectLaunch = true; 41 //押しているとき 42 } else if(Input.GetMouseButton(0)) { 43 if(scaleChange > 2.0f || 1.0f > scaleChange) { 44 scaleSwitch += 1; 45 scaleSwitch %= 2; 46 } 47 if (scaleSwitch == 1) { 48 this.scaleChange += 0.03f; 49 }else if (scaleSwitch == 0) { 50 this.scaleChange -= 0.03f; 51 } 52 if(gravityChange > 5.0f || 2.0f > gravityChange) { 53 gravitySwitch += 1; 54 gravitySwitch %= 2; 55 } 56 if (gravitySwitch == 1) { 57 this.gravityChange += 0.09f; 58 }else if (gravitySwitch == 0) { 59 this.gravityChange -= 0.09f; 60 } 61 this.transform.localScale = new Vector2(this.scaleChange, this.scaleChange); 62 } 63 } 64 } 65} 66//ボール生成のためのスクリプト 67using System.Collections; 68using System.Collections.Generic; 69using UnityEngine; 70 71public class ballGenerator : MonoBehaviour { 72 73 public GameObject ballPrefab; 74 75 76 void Update () { 77 if (Input.GetMouseButtonDown(0)) { 78 GameObject ball = 79 Instantiate(ballPrefab) as GameObject; 80 } 81 } 82} 83
試したこと
Debag.Logを使ったところstartPosの位置が左下になっていることが分かりました。
補足情報(FW/ツールのバージョンなど)
回答よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。