弓をひいて矢が飛ぶようにするにはどうすればいいでしょうか
Unityで2Dのゲームを作っています。
https://youtu.be/L0tl0CwPYIc
[Archived] Making an Angry Birds Style Game
こちらの動画を元に、スクリプトはほぼ動画のままに
パチンコの部分を弓に、球の部分を矢に変えて作りました。
発生している問題・エラーメッセージ
画面をクリックして離す(弓を引く)と矢が飛ばずに重力に従って下へ落ちていってしまいます。
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class arrowController : MonoBehaviour 6{ 7 public float maxStretch = 3.0f; 8 public LineRenderer bowLineTop; 9 public LineRenderer bowLineBottom; 10 11 private SpringJoint2D spring; 12 private Transform bow; 13 private Ray rayToMouse; 14 private Ray bottomBowToProjectile; 15 private float maxStretchSqr; 16 private float circleRadius; 17 private bool clickedOn; 18 private Vector2 prevVelocity; 19 20 void Awake() 21 { 22 spring = GetComponent <SpringJoint2D> (); 23 bow = spring.connectedBody.transform; 24 } 25 26 // Start is called before the first frame update 27 void Start() 28 { 29 LineRendererSetup(); 30 rayToMouse = new Ray(bow.position, Vector3.zero); 31 bottomBowToProjectile = new Ray(bowLineBottom.transform.position, Vector3.zero); 32 maxStretchSqr = maxStretch * maxStretch; 33 CircleCollider2D circle = GetComponent<Collider2D>() as CircleCollider2D; 34 circleRadius = circle.radius; 35 } 36 37 // Update is called once per frame 38 void Update() 39 { 40 if(clickedOn){ 41 Dragging(); 42 } 43 if(spring != null){ 44 if(!GetComponent<Rigidbody2D>().isKinematic && prevVelocity.sqrMagnitude > GetComponent<Rigidbody2D>().velocity.sqrMagnitude){ 45 Destroy(spring); 46 GetComponent<Rigidbody2D>().velocity = prevVelocity; 47 } 48 if(!clickedOn){ 49 prevVelocity = GetComponent<Rigidbody2D>().velocity; 50 } 51 LineRendererUpdate(); 52 }else{ 53 bowLineBottom.enabled = false; 54 bowLineTop.enabled = false; 55 } 56 } 57 58 void LineRendererSetup() 59 { 60 bowLineBottom.SetPosition(0, bowLineBottom.transform.position); 61 bowLineTop.SetPosition(0, bowLineTop.transform.position); 62 } 63 64 void OnMouseDown() 65 { 66 spring.enabled = false; 67 clickedOn = true; 68 } 69 70 void OnMouseUp() 71 { 72 spring.enabled = true; 73 GetComponent<Rigidbody2D>().isKinematic = false; 74 clickedOn = false; 75 } 76 77 void Dragging() 78 { 79 Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition); 80 Vector2 bowToMouse = mouseWorldPoint - bow.position; 81 if(bowToMouse.sqrMagnitude > maxStretchSqr){ 82 rayToMouse.direction = bowToMouse; 83 mouseWorldPoint = rayToMouse.GetPoint(maxStretch); 84 } 85 mouseWorldPoint.z = 0f; 86 transform.position = mouseWorldPoint; 87 } 88 89 void LineRendererUpdate() 90 { 91 Vector2 bowToProjectile = transform.position - bowLineBottom.transform.position; 92 bottomBowToProjectile.direction = bowToProjectile; 93 Vector3 holdPoint = bottomBowToProjectile.GetPoint(bowToProjectile.magnitude); 94 bowLineBottom.SetPosition(1, holdPoint); 95 bowLineTop.SetPosition(1, holdPoint); 96 } 97} 98
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/11 05:15