回答編集履歴

1

コードを画像ではなく挿入する形に変えました

2025/03/06 14:07

投稿

N-Dot
N-Dot

スコア3

test CHANGED
@@ -6,4 +6,31 @@
6
6
 
7
7
  これにより問題なく、モンスターが衝突を検知して移動するロジックをコーディングできました。
8
8
  ありがとうございました!
9
+ ```C#
10
+ //衝突時の処理
11
+ void OnCollisionEnter2D(Collision2D collision)
12
+ {
9
- ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2025-03-06/eede600b-e199-4c7f-b31b-1c0bbbd14bbe.png)
13
+ Debug.Log("Collision detected with: " + collision.gameObject.name); // デバッグログを追加
14
+ //ステージに衝突したら場合
15
+ if (collision.gameObject.layer == LayerMask.NameToLayer("Stage"))
16
+ {
17
+ ContactPoint2D contact = collision.contacts[0];//衝突した接触点の処理
18
+ Vector2 normal = contact.normal;//接触点の法線ベクトルを取得
19
+
20
+ // 衝突の法線に基づいて位置を調整
21
+ Vector2 adjustment = normal * adjust; // 調整量を設定(0.1fは適宜調整)
22
+ transform.position += (Vector3)adjustment; // 位置を調整
23
+
24
+ // 上下の衝突
25
+ if (Mathf.Abs(normal.y) > Mathf.Abs(normal.x))
26
+ {
27
+ currentDirection = new Vector2((Random.value > 0.5f) ? 1 : -1, 0); // ランダムに左右を決定
28
+ }
29
+ else // 左右の衝突
30
+ {
31
+ currentDirection = new Vector2(0, (Random.value > 0.5f) ? 1 : -1); // ランダムに上下を決定
32
+ }
33
+
34
+ }
35
+ }
36
+ ```