### 実現したいこと
Unityの3Dプラットフォームで壁に映し出された影を足場(2Dオブジェクト)とした脱出ゲームの制作をしているのですが、影の形に沿った2Dオブジェクトの作成方法が知りたい。
発生している問題・分からないこと
影の形のみを認識して2Dオブジェクトに変換する方法がわかりません。
該当のソースコード
shadowCapture.cs
1using UnityEngine; 2using System.Collections.Generic; 3 4public class ShadowCapture : MonoBehaviour 5{ 6 public Camera shadowCamera; // 影をキャプチャするカメラ 7 public RenderTexture shadowTexture; // 影をキャプチャする RenderTexture 8 public GameObject shadowColliderObject; // 影の形を持つオブジェクト 9 private Texture2D shadowImage; 10 private PolygonCollider2D polygonCollider; // 2D用のコライダー 11 12 void Start() 13 { 14 if (shadowCamera == null || shadowTexture == null || shadowColliderObject == null) 15 { 16 Debug.LogError("必要な設定が不足しています!"); 17 return; 18 } 19 20 // RenderTexture からピクセルデータを取得 21 shadowImage = new Texture2D(shadowTexture.width, shadowTexture.height, TextureFormat.RGBA32, false); 22 polygonCollider = shadowColliderObject.AddComponent<PolygonCollider2D>(); 23 24 InvokeRepeating(nameof(UpdateShadowCollider), 0.1f, 0.1f); // 影の更新(0.1秒ごと) 25 } 26 27 void UpdateShadowCollider() 28 { 29 RenderTexture.active = shadowTexture; 30 shadowImage.ReadPixels(new Rect(0, 0, shadowTexture.width, shadowTexture.height), 0, 0); 31 shadowImage.Apply(); 32 RenderTexture.active = null; 33 34 List<Vector2> shadowEdges = ExtractShadowEdges(shadowImage); 35 Debug.Log($"影のエッジ数: {shadowEdges.Count}"); 36 37 if (shadowEdges.Count > 2) 38 { 39 polygonCollider.SetPath(0, shadowEdges.ToArray()); 40 Debug.Log("PolygonCollider2D に影の形を適用しました!"); 41 } 42 } 43 44 List<Vector2> ExtractShadowEdges(Texture2D texture) 45 { 46 List<Vector2> edges = new List<Vector2>(); 47 Color[] pixels = texture.GetPixels(); 48 49 int width = texture.width; 50 int height = texture.height; 51 52 for (int y = 1; y < height - 1; y++) 53 { 54 for (int x = 1; x < width - 1; x++) 55 { 56 Color pixel = pixels[y * width + x]; 57 if (pixel.r < 0.7f) // 影の判定 58 { 59 Vector2 worldPos = shadowCamera.ScreenToWorldPoint(new Vector3(x, y, 10)); 60 edges.Add(worldPos); 61 } 62 } 63 } 64 65 return edges; 66 } 67}
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
rendertextureやレイヤーなどを使い、影の形の取得を試みたのですが、うまくいきません。
ざっくり説明するとrendertextureなどを使い、取得した影の形をtexture2Dに変換してそのデータをpollygoncolliderに当てはめるというコードにしているのですが、影の形に沿った2Dobjectは生成されません。代わりに設定したrendertextureのサイズ(512x512)の左端にのみpolygoncolliderが設定されます。
おそらく、壁に映し出された影を認識させる設定がうまくいっていないためだと思われます。
補足
Unity 2022.3.38f1

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2025/03/12 09:02