提交 a57a0de9 编写于 作者: J jakobhu 提交者: GitHub

Add navmesh script components

上级 137f5cf3
using System.Collections.Generic;
namespace UnityEngine.AI
{
[AddComponentMenu("Navigation/NavMeshLink", 33)]
[ExecuteInEditMode]
[DefaultExecutionOrder(-101)]
public class NavMeshLink : MonoBehaviour
{
[SerializeField]
int m_AgentTypeID;
public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; UpdateLink(); } }
[SerializeField]
Vector3 m_StartPoint = new Vector3(0.0f, 0.0f, -2.5f);
public Vector3 startPoint { get { return m_StartPoint; } set { m_StartPoint = value; UpdateLink(); } }
[SerializeField]
Vector3 m_EndPoint = new Vector3(0.0f, 0.0f, 2.5f);
public Vector3 endPoint { get { return m_EndPoint; } set { m_EndPoint = value; UpdateLink(); } }
[SerializeField]
float m_Width;
public float width { get { return m_Width; } set { m_Width = value; UpdateLink(); } }
[SerializeField]
bool m_Bidirectional = true;
public bool bidirectional { get { return m_Bidirectional; } set { m_Bidirectional = value; UpdateLink(); } }
[SerializeField]
bool m_AutoUpdatePosition;
public bool autoUpdate { get { return m_AutoUpdatePosition; } set { SetAutoUpdate(value); } }
[SerializeField]
int m_Area;
public int area { get { return m_Area; } set { m_Area = value; UpdateLink(); } }
NavMeshLinkInstance m_LinkInstance = new NavMeshLinkInstance();
Vector3 m_LastPosition = Vector3.zero;
Quaternion m_LastRotation = Quaternion.identity;
Vector3 m_LastScale = Vector3.one;
static readonly List<NavMeshLink> s_Tracked = new List<NavMeshLink>();
void OnEnable()
{
AddLink();
if (m_AutoUpdatePosition && m_LinkInstance.valid)
AddTracking(this);
}
void OnDisable()
{
RemoveTracking(this);
m_LinkInstance.Remove();
}
public void UpdateLink()
{
m_LinkInstance.Remove();
AddLink();
}
static void AddTracking(NavMeshLink link)
{
#if UNITY_EDITOR
if (s_Tracked.Contains(link))
{
Debug.LogError("Link is already tracked: " + link);
return;
}
#endif
if (s_Tracked.Count == 0)
NavMesh.onPreUpdate += UpdateTrackedInstances;
s_Tracked.Add(link);
}
static void RemoveTracking(NavMeshLink link)
{
s_Tracked.Remove(link);
if (s_Tracked.Count == 0)
NavMesh.onPreUpdate -= UpdateTrackedInstances;
}
void SetAutoUpdate(bool value)
{
if (m_AutoUpdatePosition == value)
return;
m_AutoUpdatePosition = value;
if (value)
AddTracking(this);
else
RemoveTracking(this);
}
void AddLink()
{
#if UNITY_EDITOR
if (m_LinkInstance.valid)
{
Debug.LogError("Link is already added: " + this);
return;
}
#endif
var link = new NavMeshLinkData();
link.startPosition = transform.TransformPoint(m_StartPoint);
link.endPosition = transform.TransformPoint(m_EndPoint);
link.width = m_Width;
link.upAxis = transform.up;
link.costModifier = -1.0f;
link.bidirectional = m_Bidirectional;
link.area = m_Area;
link.agentTypeID = m_AgentTypeID;
m_LinkInstance = NavMesh.AddLink(link);
if (m_LinkInstance.valid)
m_LinkInstance.owner = this;
m_LastPosition = transform.position;
m_LastRotation = transform.rotation;
m_LastScale = transform.lossyScale;
}
bool HasTransformChanged()
{
if (m_LastPosition != transform.position) return true;
if (m_LastRotation != transform.rotation) return true;
if (m_LastScale != transform.lossyScale) return true;
return false;
}
void OnDidApplyAnimationProperties()
{
UpdateLink();
}
static void UpdateTrackedInstances()
{
foreach (var instance in s_Tracked)
{
if (instance.HasTransformChanged())
instance.UpdateLink();
}
}
#if UNITY_EDITOR
void OnValidate()
{
if (!m_LinkInstance.valid)
return;
UpdateLink();
if (!m_AutoUpdatePosition)
{
RemoveTracking(this);
}
else if (!s_Tracked.Contains(this))
{
AddTracking(this);
}
}
#endif
}
}
using System.Collections.Generic;
namespace UnityEngine.AI
{
[AddComponentMenu ("Navigation/NavMeshModifier", 32)]
[ExecuteInEditMode]
public class NavMeshModifier : MonoBehaviour
{
[SerializeField]
bool m_OverrideArea;
public bool overrideArea { get { return m_OverrideArea; } set { m_OverrideArea = value; } }
[SerializeField]
int m_Area;
public int area { get { return m_Area; } set { m_Area = value; } }
[SerializeField]
bool m_IgnoreFromBuild;
public bool ignoreFromBuild { get { return m_IgnoreFromBuild; } set { m_IgnoreFromBuild = value; } }
// List of agent types the modifier is applied for.
// Special values: empty == None, m_AffectedAgents[0] =-1 == All.
[SerializeField]
List<int> m_AffectedAgents = new List<int> (new int[] { -1 }); // Default value is All
static readonly List<NavMeshModifier> s_NavMeshModifiers = new List<NavMeshModifier> ();
public static List<NavMeshModifier> activeModifiers
{
get { return s_NavMeshModifiers; }
}
void OnEnable ()
{
if (!s_NavMeshModifiers.Contains (this))
s_NavMeshModifiers.Add (this);
}
void OnDisable ()
{
s_NavMeshModifiers.Remove (this);
}
public bool AffectsAgentType (int agentTypeID)
{
if (m_AffectedAgents.Count == 0)
return false;
if (m_AffectedAgents[0] == -1)
return true;
return m_AffectedAgents.IndexOf (agentTypeID) != -1;
}
}
}
using System.Collections.Generic;
namespace UnityEngine.AI
{
[AddComponentMenu ("Navigation/NavMeshModifierVolume", 31)]
[ExecuteInEditMode]
public class NavMeshModifierVolume : MonoBehaviour
{
[SerializeField]
Vector3 m_Size = new Vector3 (4.0f, 3.0f, 4.0f);
public Vector3 size { get { return m_Size; } set { m_Size = value; } }
[SerializeField]
Vector3 m_Center = new Vector3 (0, 1.0f, 0);
public Vector3 center { get { return m_Center; } set { m_Center = value; } }
[SerializeField]
int m_Area;
public int area { get { return m_Area; } set { m_Area = value; } }
// List of agent types the modifier is applied for.
// Special values: empty == None, m_AffectedAgents[0] =-1 == All.
[SerializeField]
readonly List<int> m_AffectedAgents = new List<int> (new int[] { -1 }); // Default value is All
static readonly List<NavMeshModifierVolume> s_NavMeshModifiers = new List<NavMeshModifierVolume> ();
public static List<NavMeshModifierVolume> activeModifiers
{
get { return s_NavMeshModifiers; }
}
void OnEnable ()
{
if (!s_NavMeshModifiers.Contains (this))
s_NavMeshModifiers.Add (this);
}
void OnDisable ()
{
s_NavMeshModifiers.Remove (this);
}
public bool AffectsAgentType (int agentTypeID)
{
if (m_AffectedAgents.Count == 0)
return false;
if (m_AffectedAgents[0] == -1)
return true;
return m_AffectedAgents.IndexOf (agentTypeID) != -1;
}
}
}
using System.Collections.Generic;
namespace UnityEngine.AI
{
public enum CollectObjects
{
All = 0,
Volume = 1,
Children = 2,
}
[AddComponentMenu("Navigation/NavMeshSurface", 30)]
[ExecuteInEditMode]
[DefaultExecutionOrder(-102)]
public class NavMeshSurface : MonoBehaviour
{
[SerializeField]
int m_AgentTypeID;
public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; } }
[SerializeField]
CollectObjects m_CollectObjects = CollectObjects.All;
public CollectObjects collectObjects { get { return m_CollectObjects; } set { m_CollectObjects = value; } }
[SerializeField]
Vector3 m_Size = new Vector3(10.0f, 10.0f, 10.0f);
public Vector3 size { get { return m_Size; } set { m_Size = value; } }
[SerializeField]
Vector3 m_Center = new Vector3(0, 2.0f, 0);
public Vector3 center { get { return m_Center; } set { m_Center = value; } }
[SerializeField]
LayerMask m_LayerMask = ~0;
public LayerMask layerMask { get { return m_LayerMask; } set { m_LayerMask = value; } }
[SerializeField]
NavMeshCollectGeometry m_UseGeometry = NavMeshCollectGeometry.RenderMeshes;
public NavMeshCollectGeometry useGeometry { get { return m_UseGeometry; } set { m_UseGeometry = value; } }
[SerializeField]
int m_DefaultArea;
public int defaultArea { get { return m_DefaultArea; } set { m_DefaultArea = value; } }
[SerializeField]
bool m_IgnoreNavMeshAgent = true;
public bool ignoreNavMeshAgent { get { return m_IgnoreNavMeshAgent; } set { m_IgnoreNavMeshAgent = value; } }
[SerializeField]
bool m_IgnoreNavMeshObstacle = true;
public bool ignoreNavMeshObstacle { get { return m_IgnoreNavMeshObstacle; } set { m_IgnoreNavMeshObstacle = value; } }
[SerializeField]
bool m_OverrideTileSize;
public bool overrideTileSize { get { return m_OverrideTileSize; } set { m_OverrideTileSize = value; } }
[SerializeField]
int m_TileSize = 256;
public int tileSize { get { return m_TileSize; } set { m_TileSize = value; } }
[SerializeField]
bool m_OverrideVoxelSize;
public bool overrideVoxelSize { get { return m_OverrideVoxelSize; } set { m_OverrideVoxelSize = value; } }
[SerializeField]
float m_VoxelSize;
public float voxelSize { get { return m_VoxelSize; } set { m_VoxelSize = value; } }
// Currently not supported advanced options
[SerializeField]
bool m_BuildHeightMesh;
public bool buildHeightMesh { get { return m_BuildHeightMesh; } set { m_OverrideTileSize = value; } }
// Reference to whole scene navmesh data asset.
[SerializeField]
NavMeshData m_BakedNavMeshData;
public NavMeshData bakedNavMeshData { get { return m_BakedNavMeshData; } set { m_BakedNavMeshData = value; } }
// Do not serialize.
NavMeshDataInstance m_NavMeshDataInstance = new NavMeshDataInstance();
Vector3 m_LastPosition = Vector3.zero;
Quaternion m_LastRotation = Quaternion.identity;
Vector3 m_LastScale = Vector3.one;
static readonly List<NavMeshSurface> s_NavMeshSurfaces = new List<NavMeshSurface>();
public static List<NavMeshSurface> activeSurfaces
{
get { return s_NavMeshSurfaces; }
}
void OnEnable()
{
Register(this);
// Workaround: Make sure we have unique navmesh data, if not, delete reference to the data.
// HasUniqueNavMeshData () assumes that the original copy got registered before us.
if (!HasUniqueNavMeshData())
{
if (m_BakedNavMeshData != null)
{
Debug.LogWarning("Duplicating NavMeshSurface does not duplicate the referenced navmesh data");
m_BakedNavMeshData = null;
}
}
AddData();
}
void OnDisable()
{
RemoveData();
Unregister(this);
}
public void AddData()
{
if (m_NavMeshDataInstance.valid)
return;
if (m_BakedNavMeshData != null)
{
m_NavMeshDataInstance = NavMesh.AddNavMeshData(m_BakedNavMeshData, transform.position, transform.rotation);
m_NavMeshDataInstance.owner = this;
}
m_LastPosition = transform.position;
m_LastRotation = transform.rotation;
m_LastScale = transform.lossyScale;
}
public void RemoveData()
{
m_NavMeshDataInstance.Remove();
}
public NavMeshBuildSettings GetBuildSettings()
{
var buildSettings = NavMesh.GetSettingsByID(m_AgentTypeID);
if (overrideTileSize)
{
buildSettings.overrideTileSize = true;
buildSettings.tileSize = tileSize;
}
if (overrideVoxelSize)
{
buildSettings.overrideVoxelSize = true;
buildSettings.voxelSize = voxelSize;
}
return buildSettings;
}
public void Bake()
{
Bake(new NavMeshBuildDebugSettings());
}
public void Bake(NavMeshBuildDebugSettings debug)
{
var sources = CollectSources();
// Use unscaled bounds - this differs in behaviour from e.g. collider components.
// But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here
var sourcesBounds = new Bounds(m_Center, Abs(m_Size));
if (m_CollectObjects == CollectObjects.All || m_CollectObjects == CollectObjects.Children)
{
sourcesBounds = CalculateWorldBounds(sources);
}
var data = NavMeshBuilder.BuildNavMeshData(GetBuildSettings(),
sources, sourcesBounds, transform.position, transform.rotation, debug);
if (data != null)
{
data.name = gameObject.name;
RemoveData();
m_BakedNavMeshData = data;
AddData();
}
}
static void Register(NavMeshSurface surface)
{
if (s_NavMeshSurfaces.Count == 0)
NavMesh.onPreUpdate += UpdateActive;
if (!s_NavMeshSurfaces.Contains(surface))
s_NavMeshSurfaces.Add(surface);
}
static void Unregister(NavMeshSurface surface)
{
s_NavMeshSurfaces.Remove(surface);
if (s_NavMeshSurfaces.Count == 0)
NavMesh.onPreUpdate -= UpdateActive;
}
static void UpdateActive()
{
for (var i = 0; i < s_NavMeshSurfaces.Count; ++i)
s_NavMeshSurfaces[i].UpdateDataIfTransformChanged();
}
bool HasUniqueNavMeshData()
{
for (var i = 0; i < s_NavMeshSurfaces.Count; ++i)
{
var surface = s_NavMeshSurfaces[i];
if (surface != this && surface.m_BakedNavMeshData == m_BakedNavMeshData)
return false;
}
return true;
}
void AppendModifierVolumes(ref List<NavMeshBuildSource> sources)
{
// Modifiers
List<NavMeshModifierVolume> modifiers;
if (m_CollectObjects == CollectObjects.Children)
{
modifiers = new List<NavMeshModifierVolume>(GetComponentsInChildren<NavMeshModifierVolume>());
modifiers.RemoveAll(x => !x.isActiveAndEnabled);
}
else
{
modifiers = NavMeshModifierVolume.activeModifiers;
}
foreach (var m in modifiers)
{
if ((m_LayerMask & (1 << m.gameObject.layer)) == 0)
continue;
if (!m.AffectsAgentType(m_AgentTypeID))
continue;
var mcenter = m.transform.TransformPoint(m.center);
var scale = m.transform.lossyScale;
var msize = new Vector3(m.size.x * Mathf.Abs(scale.x), m.size.y * Mathf.Abs(scale.y), m.size.z * Mathf.Abs(scale.z));
var src = new NavMeshBuildSource();
src.shape = NavMeshBuildSourceShape.ModifierBox;
src.transform = Matrix4x4.TRS(mcenter, m.transform.rotation, Vector3.one);
src.size = msize;
src.area = m.area;
sources.Add(src);
}
}
List<NavMeshBuildSource> CollectSources()
{
var sources = new List<NavMeshBuildSource>();
var markups = new List<NavMeshBuildMarkup>();
List<NavMeshModifier> modifiers;
if (m_CollectObjects == CollectObjects.Children)
{
modifiers = new List<NavMeshModifier>(GetComponentsInChildren<NavMeshModifier>());
modifiers.RemoveAll(x => !x.isActiveAndEnabled);
}
else
{
modifiers = NavMeshModifier.activeModifiers;
}
foreach (var m in modifiers)
{
if ((m_LayerMask & (1 << m.gameObject.layer)) == 0)
continue;
if (!m.AffectsAgentType(m_AgentTypeID))
continue;
var markup = new NavMeshBuildMarkup();
markup.root = m.transform;
markup.overrideArea = m.overrideArea;
markup.area = m.area;
markup.ignoreFromBuild = m.ignoreFromBuild;
markups.Add(markup);
}
if (m_CollectObjects == CollectObjects.All)
{
NavMeshBuilder.CollectSources(null, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
else if (m_CollectObjects == CollectObjects.Children)
{
NavMeshBuilder.CollectSources(transform, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
else if (m_CollectObjects == CollectObjects.Volume)
{
Matrix4x4 localToWorld = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
var worldBounds = GetWorldBounds(localToWorld, new Bounds(m_Center, m_Size));
NavMeshBuilder.CollectSources(worldBounds, m_LayerMask, m_UseGeometry, m_DefaultArea, markups, sources);
}
if (m_IgnoreNavMeshAgent)
sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent<NavMeshAgent>() != null));
if (m_IgnoreNavMeshObstacle)
sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent<NavMeshObstacle>() != null));
AppendModifierVolumes(ref sources);
return sources;
}
static Vector3 Abs(Vector3 v)
{
return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z));
}
static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds)
{
var absAxisX = Abs(mat.MultiplyVector(Vector3.right));
var absAxisY = Abs(mat.MultiplyVector(Vector3.up));
var absAxisZ = Abs(mat.MultiplyVector(Vector3.forward));
var worldPosition = mat.MultiplyPoint(bounds.center);
var worldSize = absAxisX * bounds.size.x + absAxisY * bounds.size.y + absAxisZ * bounds.size.z;
return new Bounds(worldPosition, worldSize);
}
Bounds CalculateWorldBounds(List<NavMeshBuildSource> sources)
{
// Use the unscaled matrix for the NavMeshSurface
Matrix4x4 worldToLocal = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one);
worldToLocal = worldToLocal.inverse;
var result = new Bounds();
foreach (var src in sources)
{
switch (src.shape)
{
case NavMeshBuildSourceShape.Mesh:
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, src.mesh.bounds));
break;
case NavMeshBuildSourceShape.Terrain:
{
// Terrain pivot is lower/left corner - shift bounds accordingly
var tsize = src.terrainData.size;
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(0.5f * tsize, tsize)));
break;
}
case NavMeshBuildSourceShape.Box:
case NavMeshBuildSourceShape.Sphere:
case NavMeshBuildSourceShape.Capsule:
case NavMeshBuildSourceShape.ModifierBox:
result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(Vector3.zero, src.size)));
break;
}
}
// Inflate the bounds a bit to avoid clipping co-planar sources
result.Expand(0.1f);
return result;
}
bool HasTransformChanged()
{
if (m_LastPosition != transform.position) return true;
if (m_LastRotation != transform.rotation) return true;
if (m_LastScale != transform.lossyScale) return true;
return false;
}
void UpdateDataIfTransformChanged()
{
if (HasTransformChanged())
{
RemoveData();
AddData();
}
}
#if UNITY_EDITOR
void OnValidate()
{
if (!s_NavMeshSurfaces.Contains(this))
return;
var settings = NavMesh.GetSettingsByID(m_AgentTypeID);
if (settings.agentTypeID != -1)
{
// When unchecking the override control, revert to automatic value.
const float kMinVoxelSize = 0.01f;
if (!m_OverrideVoxelSize)
m_VoxelSize = settings.agentRadius / 3.0f;
if (m_VoxelSize < kMinVoxelSize)
m_VoxelSize = kMinVoxelSize;
// When unchecking the override control, revert to default value.
const int kMinTileSize = 16;
const int kMaxTileSize = 1024;
const int kDefaultTileSize = 256;
if (!m_OverrideTileSize)
m_TileSize = kDefaultTileSize;
// Make sure tilesize is in sane range.
if (m_TileSize < kMinTileSize)
m_TileSize = kMinTileSize;
if (m_TileSize > kMaxTileSize)
m_TileSize = kMaxTileSize;
}
}
#endif
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册