[Unity] RPG 想隨機生怪,又不想怪生在石頭上 水中 等卡點的地方解決辦法 NavMesh.SamplePosition

想要在一整片開放地圖,隨機生怪,又不想用點位,一一設定的話,可以用NavMesh.SamplePosition

但是先決條件是你的地圖是透過 NavMesh 去Bake路線的,

才能夠使用這個辦法

# NavMesh  參考資料 : https://docs.unity3d.com/ScriptReference/AI.NavMesh.html
                                       https://jerrard-liu.blogspot.com/2016/07/NavMeshBaking.html

如果要在可走的地方隨機生怪可以用以下方法

       public struct OptPos {
            public bool ok;
            public Vector3 pos;
        }  

       private OptPos randomOptPos(Vector3 pos) {

            NavMeshHit hit;
            if (NavMesh.SamplePosition(pos, out hit, 1.0f, NavMesh.AllAreas)) {
                return new OptPos() {
                    ok = true,
                    pos = hit.position
                };
            }

            return new OptPos() {
                pos = pos
            };
        }

留言

這個網誌中的熱門文章

angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學