Unity2Dの横スクロールのゲームです。
クリックをしたら物体を生成し引っ張って投げるアングリーバードのような処理を作りました。
今回はアングリーバードのような固定の発射場所ではなくPlayerの場所に物体を生成しそこから投げます。
そこで以下のコードをPlayerの子に作ったspawnPointに入れました。
Update内のコメント化した部分を入れると移動中に保持してくれますがマウスを離した時にうまく飛んでくれません。コメント部分がなしだとちゃんと飛んでくれます。
どうすればいいでしょうか。
追記
コメント化した部分をFixedUpdateに入れてみたところ、追従して投げも上手くいきますがNullReferenceException: Object reference not set to an instance of an object
BombThrow.FixedUpdate のエラーが出るのと、爆弾が少しずつ下に移動してしまいます。
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class BombThrow : MonoBehaviour 6{ 7 Vector3 startP, endP; 8 public float throwPower, coefficient; 9 10 public GameObject bomb; 11 GameObject newBomb; 12 // Start is called before the first frame update 13 void Start() 14 { 15 16 } 17 18 // Update is called once per frame 19 void Update() 20 { 21 if (Input.GetMouseButtonDown(0)) 22 { 23 //生成 24 newBomb = Instantiate(this.bomb, this.transform.position 25 , Quaternion.identity); 26 //マウスの開始位置 27 startP = Input.mousePosition; 28 } 29 30 ////移動中も保持したい 31 //if (Input.GetMouseButton(0)) 32 //{ 33 // newBomb.transform.position = this.transform.position; 34 //} 35 36 if (Input.GetMouseButtonUp(0)) 37 { 38 //マウスの終了位置 39 endP = Input.mousePosition; 40 //投る 41 var velosity = (startP - endP).normalized * throwPower; 42 newBomb.GetComponent<Rigidbody2D>().AddForce(coefficient * velosity); 43 } 44 } 45}
回答2件
あなたの回答
tips
プレビュー