実現したいこと
プレイヤーをジャンプできるようにする。
発生している問題・分からないこと
ジャンプキーをレイヤーがGroundの場所で押してもジャンプしない。
該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class PLYRCTRLR : MonoBehaviour 6{ 7 //rigidbody2D型の変数 8 Rigidbody2D rb2d; 9 //入力 10 float axisH = 0.0f; 11 //移動速度 12 public float speed = 3.0f; 13 14 //ジャンプ力 15 public float jump = 9.0f; 16 //着地できるレイヤー 17 public LayerMask GroundLayer; 18 bool goJump = false; 19 // Start is called before the first frame update 20 void Start() 21 { 22 //rigidbodyを取得 23 rb2d = this.GetComponent<Rigidbody2D>(); 24 } 25 26 // Update is called once per frame 27 void Update() 28 { 29 //水平方向の入力をチェック 30 axisH = Input.GetAxisRaw("Horizontal"); 31 if (axisH > 0.0f) 32 { 33 //右移動 34 transform.localScale = new Vector2(1, 1); 35 } 36 else if (axisH < 0.0f) 37 { 38 //左移動 39 transform.localScale = new Vector2(-1,1); //左右反転させる 40 } 41 42 //キャラクターをジャンプさせる 43 if (Input.GetButtonDown("Jump")) 44 { 45 Jump(); 46 } 47 } 48 49 void FixedUpdate() 50 { 51 //地上判定 52 bool onGround = Physics2D.CircleCast(transform.position, 0.2f, Vector2.down, 0.0f, GroundLayer);//BUG 53 if (onGround || axisH != 0) 54 { 55 //地面の上 又は 速度が0でない 56 //速度を更新 57 rb2d.velocity = new Vector2(axisH * speed, rb2d.velocity.y); 58 } 59 if(onGround && goJump) 60 { 61 //地面の上でジャンプキーが押された 62 //ジャンプさせる 63 Vector2 jumpPw = new Vector2(0, jump); //ジャンプさせるベクトルを作る 64 rb2d.AddForce(jumpPw, ForceMode2D.Impulse); //瞬間的な力を与える 65 goJump = false; 66 } 67 } 68 //ジャンプ 69 public void Jump() 70 { 71 goJump = true; //ジャンプフラグを立てる 72 } 73} 74
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
Debug.Logを使って//BUGと書かれているところに原因がありそうだと分かった。
補足
ジャンプキーとはスペースキーのことです。
バージョンは2022.3.15f1です。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2024/05/18 02:01 編集