実現したいこと
モンスターがブロックのない場所を移動するようにしたいです。
発生している問題・分からないこと
X垢のほうでバグ時の動画上げてます
現在OnCollisionメソッドを用いてステージレイヤーを持たせたブロックとの衝突を感知、Vector2によって移動方向を反転させています。また、左右移動中の予期せぬ上下との衝突を避けるためにモンスターの当たり判定の半径を少し小さくし、衝突時に位置調整も行っています。
左右のみ、上下のみでの衝突による反転は問題なかったのですが、左右の衝突によって上下に移動するようにコードを書き換えたところブロックにめり込んでしまい、モンスターがブロック上も移動してしまいます。
該当のソースコード
C#
1 //衝突時の処理 2 void OnCollisionEnter2D(Collision2D collision) 3 { 4 Debug.Log("Collision detected with: " + collision.gameObject.name); // デバッグログを追加 5 //ステージに衝突したら場合 6 if (collision.gameObject.layer == LayerMask.NameToLayer("Stage")) 7 { 8 ContactPoint2D contact = collision.contacts[0];//衝突した接触点の処理 9 Vector2 normal = contact.normal;//接触点の法線ベクトルを取得 10 11 if(currentDirection == Vector2.up || currentDirection == Vector2.down)//上下の衝突 12 { 13 if(normal.y < 0) adjust = -adjust; 14 else adjust = adjust; 15 currentDirection = new Vector2(0, 0);//上下の移動をやめる 16 transform.position = new Vector2(transform.position.x, transform.position.y + adjust); 17 currentDirection = (Random.value > 0.5f) ? Vector2.right : Vector2.left;//ランダムに左右を決定 18 } 19 else//左右の衝突 20 { 21 if(normal.x < 0) adjust = adjust; 22 else adjust = -adjust; 23 currentDirection = new Vector2(0, 0); 24 transform.position = new Vector2(transform.position.x + adjust, transform.position.y); 25 currentDirection = (Random.value > 0.5f) ? Vector2.up : Vector2.down;//ランダムに上下を決定` 26 } 27 28 // 方向を反転させる 29 if (currentDirection == Vector2.right) 30 { 31 currentDirection = Vector2.left; // 反対方向に変更 32 } 33 else if (currentDirection == Vector2.left) 34 { 35 currentDirection = Vector2.right; // 反対方向に変更 36 } 37 else if (currentDirection == Vector2.up) 38 { 39 currentDirection = Vector2.down; // 反対方向に変更 40 } 41 else if (currentDirection == Vector2.down) 42 { 43 currentDirection = Vector2.up; // 反対方向に変更 44 } 45 } 46 }
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
おそらく、連続した一方向への移動が原因と考えています。
例えば、右方向への衝突後上下移動に変更、上下衝突により左右移動へ←ここで右方向へ変更されたときにめり込んでる?
補足
特になし

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2025/03/06 13:55