前言:Unity版本为2019.2.9f1 Ppersonal。Unity版本可在上方Help下点击About Unity找到。本文将采用官方文档的英文并对比介绍。由于个人英文和开发水平有限,翻译或解释不到位的地方还请原谅。个别方法鉴于目前还没使用过,不好做过多介绍,只好先贴出来以供暂时理解即可。看完觉得有帮助还请点个赞,还想看其他文章的也请加个关注哦~喵。
文章目录
- NavMeshAgent
- Properties
- Insepecotr
- 非Inspector
- avoidancePriority(int)
- currentOffMeshLinkData(AI.OffMeshLinkData)
- desiredVelocity(Vector3)
- destination(Vector3)
- hasPath(bool)
- isOnNavMesh(bool)
- isOnOffMeshLink(bool)
- isPathStale(bool)
- isStopped(bool)
- navMeshOwner(Object)
- nextOffMeshLinkData(AI.OffMeshLinkData)
- nextPosition(Vector3)
- obstacleAvoidanceType(AI.ObstacleAvoidanceType)
- path(AI.NavMeshPath)
- pathPending(bool)
- pathStatus(AI.NavMeshPathStatus)
- steeringTarget(Vector3)
- updatePosition(bool)
- updateRotation(bool)
- updateUpAxis(bool)
- velocity(Vector3)
- API(Public Methods)
NavMeshAgent
Properties
Insepecotr
This component is attached to a mobile character in the game to allow it to navigate the Scene using the NavMesh. See the Navigation section of the manual for further details.
该组件附加在游戏中一个可移动的人物上,从而允许它使用NavMesh在Scene中导航。简单地说,该组件提供了自动寻路的功能。
阅读前须知:
我们将游戏对象GameObject上挂载的NavMeshAgent组件称为Agent。我们用代码,通过对Agent进行调整来移动GameObject,所以通常来讲Agent指代的就是游戏对象。但Agent依然是一个组件,只不过它控制着GameObject的运动而已。
我们将地图上Agent可穿行的区域称为NavMesh,即导航网格。
Agent Type
The type ID for the agent.
This identifier determines which NavMeshes are available for the Agent to move on. See also NavMeshBuildSettings.agentTypeID. Changing this ID will reset the Agent’s current path.
这个标识符决定了Agent可以在哪些NavMeshes上移动。另请参见NavMeshBuildSettings.agentTypeID。改变Agent Type将重置Agent的当前路径。
该设置在Navigation中,Navigation可在Windows下的AI中找到。打开后,就能见到如图所示的Agent Type了。该值的设置相当于人物的分类,比如你可以新建一个Animal的Agent Type,然后设置其相关的属性。这样在寻路时就会表现出与Humanoid不同的特征。
Base Offset
The relative vertical displacement of the owning GameObject.
游戏对象的垂直相对位移。即agent的Y轴偏移,正值往下,负值往上。
Steering(操纵)
Steering内的参数一般都不在Inspector界面调整它,而是在代码中进行设置。
Speed(float)
Maximum movement speed when following a path.
An agent will typically need to speed up and slow down as it follows a path (eg, it will slow down to make a tight turn). The speed is often limited by the length of a path segment and the time taken to accelerate and brake, but the speed will not exceed the value set by this property even on a long, straight path.
寻路时的最大移动速度。设置该数值为0并不能使得agent立刻停下,具体见IsStopped。
Angular Speed(float)
Maximum turning speed in (deg/s) while following a path.
This is the maximum rate at which the agent can turn as it rounds the “corner” defined by a waypoint. The actual turning circle is also influenced by the speed of the agent on approach and also the maximum acceleration.
寻路时的最大转向速度(最大角速度)。值越大,agent的转向越迅速。
Acceleration(float)
The maximum acceleration of an agent as it follows a path, given in units / sec^2.
An agent does not follow precisely the line segments of the path calculated by the navigation system but rather uses the waypoints along the path as intermediate destinations. This value is the maximum amount by which the agent can accelerate while moving towards the next waypoint.
当agent寻路时的最大加速度。单纯物理意义上的加速度,控制速度变化的快慢。
Stopping Distance(float)
Stop within this distance from the target position.
It is seldom possible to land exactly at the target point, so this property can be used to set an acceptable radius within which the agent should stop. A larger stopping distance will give the agent more room for manoeuvre at the end of the path and might avoid sudden braking, turning or other unconvincing AI behaviour.
制动距离。当agent与目标点的距离小于它时会自动停下来以免越过目标点。
Auto Braking(bool)
Should the agent brake automatically to avoid overshooting the destination point?
If the agent needs to land close to the destination point then it will typically need to brake to avoid overshooting or endless “orbiting” around the target zone. If this property is set to true, the agent will brake automatically as it nears the destination.
该属性设置为true时,agent会在到达Stopping Distance时直接停下。否则会出现当agent速度太快冲过目标点时,会缓慢的回到目标点的现象。
Obstacle Avoidance(障碍回避)
这下面调节的都是agent空间参数。在Unity中,agent是一个圆柱形的范围空间,所有的AI智能寻路都是基于agent的参数设置。它相当于是一个有着触发器属性(ISTrigger)的Collider,但并不是一个触发器甚至是碰撞器。
Radius(float)
The avoidance radius for the agent.
This is the agent’s “personal space” within which obstacles and other agents should not pass.
agent的躲避半径。相当于agent的私人空间,在这个半径内其它障碍或agent无法穿过。
Height(float)
The height of the agent for purposes of passing under obstacles, etc.
agent的高度。低于该值的障碍agent都无法穿过。
Quality(enum)
设置质量。我也不知道这个有什么用,设置成High Quality就好了。
priority(int)
优先级。低优先级的agent会给高优先级的agent让路。
Pathing Finding(寻路)
autoTraverseOffMeshLink(bool)
Should the agent move across OffMeshLinks automatically?
Off-mesh links are used to connect disjoint regions of the NavMesh. Usually, a character should be able to pass through or traverse a link automatically, which will happen if this property is set to true. However, it can also be set to false in cases where special control over movement is needed.
分离网格链接指的是两个不相交的导航网格之间的链接路径(比如agent跳过去飞过去等非实地路径)。关于这个的详细内容可以参看这篇博客【Unity】12.3 Off Mesh Link组件。简单来说,该值设置为true的话,agent将可以通过分离网格链接。将其设置为false的话,就需要你手动的给场景中的物体添加Off Mesh Link组件,从而使得agent可以到达其上。
autoRepath(bool)
Should the agent attempt to acquire a new path if the existing path becomes invalid?
A new path calculation is also attempted acquired if the agent reaches the end of a partial and stale path.
该值默认为true,agent会在到达一条局部或过时的路径末端时重新规划一条路径。如果你希望通过代码来调控它的路径选择,你可以在Start中将其设置为false以免多次计算。
areaMask(int)
Specifies which NavMesh areas are passable. Changing areaMask will make the path stale (see isPathStale).
This is a bitfield.
该值指明哪些NavMesh是可通行的。
非Inspector
avoidancePriority(int)
The avoidance priority level.
When the agent is performing avoidance, agents of lower priority are ignored. The valid range is from 0 to 99 where: Most important = 0. Least important = 99. Default = 50.
回避优先级。当agent执行回避操作时会忽略掉低优先级的agents。0-99都是有效的范围。其中,0是最高优先级,99最低,默认为50。
currentOffMeshLinkData(AI.OffMeshLinkData)
The current OffMeshLinkData.
In the case that this agent is not on an OffMeshLink the OffMeshLinkData is marked as invalid.
当前的分离网格链接数据。在某种情况下agent不在分离网格的链接上时,分离网格的链接数据会被标记为无效的。
desiredVelocity(Vector3)
The desired velocity of the agent including any potential contribution from avoidance. (Read Only)
agent的预期速度,其中包括任何来自障碍的潜在限制。因此它并不是一个定值。
destination(Vector3)
Gets or attempts to set the destination of the agent in world-space units.
Getting:
Returns the destination set for this agent.
- If a destination is set but the path is not yet processed the position returned will be valid navmesh position that’s closest to the previously set position.
- If the agent has no path or requested path - returns the agents position on the navmesh.
- If the agent is not mapped to the navmesh (e.g. Scene has no navmesh) - returns a position at infinity.
Setting:
Requests the agent to move to the valid navmesh position that’s closest to the requested destination.
- The path result may not become available until after a few frames. Use pathPending to query for outstanding results.
- If it’s not possible to find a valid nearby navmesh position (e.g. Scene has no navmesh) no path is requested. Use SetDestination and check return value if you need to handle this case explicitly.
hasPath(bool)
Does the agent currently have a path? (Read Only)
This property will be true if the agent has a path calculated to the desired destination and false otherwise.
agent是否已经计算出了一条前往预定目的地的路径。
isOnNavMesh(bool)
Is the agent currently bound to the navmesh? (Read Only)
This property is false if the agent, for some reason, could not bind to the navmesh. E.g. if Scene has no navmesh.
该值为true时表明agent在导航网格上。
isOnOffMeshLink(bool)
Is the agent currently positioned on an OffMeshLink? (Read Only)
This property is useful when autoTraverseOffMeshLink is false and custom movement is needed when crossing the link.
同上isOnNavMesh。
isPathStale(bool)
Is the current path stale. (Read Only)
When true, the path may no longer be valid or optimal. This flag will be set if: there are any changes to the areaMask, if any OffMeshLink is enabled or disabled, or if the costs for the NavMeshAreas have been changed.
该值为true表明路径不再有效或者并不是最佳的。当areaMask被改变时,或任意一个分离网格链接被启用或禁用时,或某一导航网格区域的代价被改变时,都会使得该值变为true。
isStopped(bool)
This property holds the stop or resume condition of the NavMesh agent.
If set to True, the NavMesh agent’s movement will be stopped along its current path. If set to False after the NavMesh agent has stopped, it will resume moving along its current path.
该属性保存agent的停止或恢复条件。
该值为true,agent的移动将沿着其当前路径停止。 如果在agent寻路时将该属性设置为false,它将会因为惯性继续沿着它当前的寻路路径移动一小段距离。
navMeshOwner(Object)
Returns the owning object of the NavMesh the agent is currently placed on (Read Only).
If no owner is set for a NavMesh or link instance the return value is null.
返回agent当前所处导航网格的拥有者。如果该导航网格没有拥有者,或者没有链接实例,那么它会返回null。
nextOffMeshLinkData(AI.OffMeshLinkData)
The next OffMeshLinkData on the current path.
In the case that the current path does not contain an OffMeshLink the OffMeshLinkData is marked as invalid.
当前路径的下一个OffMeshLinkData。在某种情况下,当前路径并不包含一个分离网格链接,那么下一个分离网格链接就会被标记为无效。
nextPosition(Vector3)
Gets or sets the simulation position of the navmesh agent.
The position vector is in world space coordinates and units.
The nextPosition is coupled to Transform.position. In the default case the navmesh agent’s Transform position will match the internal simulation position at the time the script Update function is called. This coupling can be turned on and off by setting updatePosition.
When updatePosition is true, the Transform.position reflects the simulated position, when false the position of the transform and the navmesh agent is not synchronized, and you’ll see a difference between the two in general. When updatePosition is turned back on, the Transform.position will be immediately move to match nextPosition.
By setting nextPosition you can directly control where the internal agent position should be. The agent will be moved towards the position, but is constrained by the navmesh connectivity and boundaries. As such it will be useful only if the positions are continuously updated and assessed.
获取或设置导航网格代理的模拟位置。
位置向量采用的是空间坐标和单位。
nextPosition被耦合到了变换位置上。在默认情况下导航网格代理的变换位置会在脚本中的Update方法被调用时匹配到局部的模拟位置。这种耦合可以通过设置updatePosition来打开或关闭。
当updatePosition为true时,变换位置映射出模拟的位置。反之变换位置和导航网格代理就是不同步的,如果你这么设置就可以看到两者在运动的过程中分离开来。当updatePosition被重新打开时,变换位置将会立即被移去匹配nextPosition。
通过设置nextPosition,你可以直接控制局部的agent位置应该处于的地方。agent将会被移去指定的位置,但是会受到导航网格连接性和边界的限制。因此它只有在位置是不停地更新或评估时才有用。
obstacleAvoidanceType(AI.ObstacleAvoidanceType)
The level of quality of avoidance.
This property lets you trade off the precision of obstacle avoidance againt the processor load required to achieve it. The exact quality/performance values will depend heavily on the complexity of the Scene but as a general rule, faster performance can be achieved at the cost of quality and vice versa.
path(AI.NavMeshPath)
Property to get and set the current path.
This property can be useful for GUI, debugging and other purposes to get the points of the path calculated by the navigation system. Additionally, a path created from user code can be set for the agent to follow in the usual way. An example of this might be a patrol route designed for coverage rather than optimal distance between two points.
pathPending(bool)
Is a path in the process of being computed but not yet ready? (Read Only)
该值为true表明路径正在计算中但还没有准备好。
pathStatus(AI.NavMeshPathStatus)
The status of the current path (complete, partial or invalid).
当前路径的状态,比如是否完整、局部、无效的。
steeringTarget(Vector3)
Get the current steering target along the path. (Read Only)
This is typically the next corner along the path or the end point of the path.
Unless the agent is moving on an OffMeshLink, there is a straight path between the agent and the steeringTarget.
When approaching an OffMeshLink for traversal - the value is the position where the agent will enter the link. While agent is traversing an OffMeshLink the value is the position where the agent will leave the link.
updatePosition(bool)
Gets or sets whether the transform position is synchronized with the simulated agent position. The default value is true.
When true: changing the transform position will affect the simulated position and vice-versa.
When false: the simulated position will not be applied to the transform position and vice-versa.
Setting updatePosition to false can be used to enable explicit control of the transform position via script. This allows you to use the agent’s simulated position to drive another component, which in turn sets the transform position (eg. animation with root motion or physics).
When enabling the updatePosition (from previously being disabled), the transform will be moved to the simulated position. This way the agent stays constrained to the navmesh surface.
获取或设置游戏对象的变换位置是否与模拟的agent的位置同步,默认值是true。
如果为true,则改变对象的变换位置将会影响模拟的位置(agent的位置),反之亦然。
如果为false:模拟位置将不会应用于变换位置,反之亦然。
将updatePosition设置为false可用于通过脚本对变换位置启用明确的控制。 这样我们就可以使用agent的模拟位置来驱动另一个组件,从而设置变换位置(例如,具有根运动或物理特性的动画)。
将updatePosition从禁用改为启用时,变换位置将会被移去匹配模拟位置。从而agent就被约束地在导航网格表面。
updateRotation(bool)
Should the agent update the transform orientation?
同updatePosition。
要注意的是,将updatePosition以及updateRotation设置为false的话,SetDestination就只会使得agent去寻路,而游戏对象会保持不动。由此我们可以知道,是agent的位置或旋转带动游戏对戏的变换位置或旋转。直接设置这两个值并不会使得agent停下,只是不让它的位置和挂载对象的变换位置或旋转同步而已。知道这个后,我们就可以在每一帧通过如下语句来使得物体到达目标点后立即停下。它的工作原理便是让agent的位置或旋转,在每一帧都强制等于游戏对象的位置或旋转上。
m_NavMeshAgent.updatePosition = false;
m_NavMeshAgent.updateRotation = false;
m_NavMeshAgent.nextPosition = transform.position;
另请参见nextPosition。
updateUpAxis(bool)
Allows you to specify whether the agent should be aligned to the up-axis of the NavMesh or link that it is placed on.
When this value is set to true, the agent will always be aligned to the local up-axis of the NavMesh or link that it is currently on. When set to false, the agent’s orientation is unaffected by the orientation of the NavMesh.
velocity(Vector3)
Access the current velocity of the NavMeshAgent component, or set a velocity to control the agent manually.
Reading the variable will return the current velocity of the agent based on the crowd simulation.
Setting the variable will override the simulation (including: moving towards destination, collision avoidance, and acceleration control) and command the NavMesh Agent to move using the specific velocity directly. When the agent is controlled using a velocity, its movement is still constrained on the NavMesh.
Setting the velocity directly, can be used for implementing player characters, which are moving on NavMesh and affecting the rest of the simulated crowd. In addition, setting priority to high (a small value is higher priority), will make other simulated agents to avoid the player controlled agent even more eagerly.
It is recommended to set the velocity each frame when controlling the agent manually, and if releasing the control to the simulation, set the velocity to zero. If agent’s velocity is set to some value and then stopped updating it, the simulation will pick up from there and the agent will slowly decelerate (assuming no destination is set).
Note that reading the velocity will always return value from the simulation. If you set the value, the effect will show up in the next update. Since the returned velocity comes from the simulation (including avoidance and collision handling), it can be different than the one you set.
The velocity is specified in distance units per second (same as physics), and represented in global coordinate system.
API(Public Methods)
ActivateCurrentOffMeshLink(void)
public void ActivateCurrentOffMeshLink(bool activated);
Parameters | Description |
---|---|
actived | Is the link activated? |
Enables or disables the current off-mesh link.
This function activates or deactivates the off-mesh link where the agent is currently waiting. This is useful for granting access to newly discovered areas of the game world or simulating the creation or removal of an obstacle to an area.
启用或禁用当前的分离网格链接。
该方法激活或停用agent当前正在等待的分离网格链接。这有助于授权agent对象访问游戏世界的新发现的区域,或者模拟出对某个区域的障碍物的创造或移除。
总的来说,我也不知道这个方法有什么用。
CalculatePath(bool)
public bool CalculatePath(Vector3 targetPosition, AI.NavMeshPath path);
Parameters | Description |
---|---|
targetPosition | The final position of the path requested. |
path | The resulting path. |
Return | bool True if a path is found. |
Calculate a path to a specified point and store the resulting path.
This function can be used to plan a path ahead of time to avoid a delay in gameplay when the path is needed. Another use is to check if a target position is reachable before moving the agent.
CompleteOffMeshLink(void)
public void CompleteOffMeshLink();
Completes the movement on the current OffMeshLink.
The agent will move to the closest valid navmesh position on the other end of the current OffMeshLink.
CompleteOffMeshLink has no effect unless the agent is on an OffMeshLink (See Also: isOnOffMeshLink).
When autoTraverseOffMeshLink is disabled an agent will pause at an off-mesh link until this function is called. It is useful for implementing custom movement across OffMeshLinks.
FindClosestEdge(bool)
public bool FindClosestEdge(out AI.NavMeshHit hit);
Parameters | Description |
---|---|
hit | Holds the properties of the resulting location. |
Return | bool True if a nearest edge is found. |
Locate the closest NavMesh edge.
The returned NavMeshHit object contains the position and details of the nearest point on the nearest edge of the Navmesh. Since an edge typically corresponds to a wall or other large object, this could be used to make a character take cover as close to the wall as possible.
GetAreaCost(float)
public float GetAreaCost(int areaIndex);
areaIndex Area Index.
Returns
float Current cost for specified area index.
Parameters | Description |
---|---|
areaIndex | Area Index. |
Return | float Current cost for specified area index. |
Gets the cost for path calculation when crossing area of a particular type.
The cost of a path is the amount of “difficulty” involved in calculating it - the shortest path may not be the best if it passes over difficult ground, such as mud, snow, etc. Different types of areas are denoted by navmesh areas in Unity. The cost of a particular area is given in cost units per distance unit. Note that the cost of a path applies to the pathfinding only and does not automatically affect the movement speed of the agent when following the path. Indeed, the path’s cost may denote other factors such as danger (safe but long path through a minefield) or visibility (long path that keeps a character in the shadows).
Move(Vector3)
public void Move(Vector3 offset);
Parameters | Description |
---|---|
offset | The relative movement vector. |
Apply relative movement to current position.
If the agent has a path it will be adjusted.
不常用的方法。直接给agent提供一个运动的方向,它会朝着这个方向一直运动。前提是它在导航网格上。如果agent正在寻路,那么该方法会被打断。
Raycast(bool)
public bool Raycast(Vector3 targetPosition, out AI.NavMeshHit hit);
Parameters | Description |
---|---|
targetPosition | The desired end position of movement. |
hit | Properties of the obstacle detected by the ray (if any). |
Return | bool True if there is an obstacle between the agent and the target position, otherwise false. |
Trace a straight path towards a target postion in the NavMesh without moving the agent.
This function follows the path of a “ray” between the agent’s position and the specified target position. If an obstruction is encountered along the line then a true value is returned and the position and other details of the obstructing object are stored in the hit parameter. This can be used to check if there is a clear shot or line of sight between a character and a target object. This function is preferable to the similar Physics.Raycast because the line tracing is performed in a simpler way using the navmesh and has a lower processing overhead.
ResetPath(void)
public void ResetPath();
Clears the current path.
When the path is cleared, the agent will not start looking for a new path until SetDestination is called.
Note that if the agent is on an OffMeshLink when this function is called, it will complete the link immediately.
清除当前路径。
路径被清除后,agent不会再次寻找新的路径,直到SetDestination方法被调用。有一点需要注意,当agent正在一个分离网格链接上时(比如正在从一个建筑物跳到另一个建筑物的过程中)调用该方法,它会立即完成这一链接动作(表现出来就是立刻闪烁到另一个建筑物上)。
还需要注意的是,清除路径并不意味着使agent停下,只是不再寻找新的路径而已。
SamplePathPosition(bool)
public bool SamplePathPosition(int areaMask, float maxDistance, out AI.NavMeshHit hit);
Parameters | Description |
---|---|
areaMask | A bitfield mask specifying which NavMesh areas can be passed when tracing the path. |
maxDistance | Terminate scanning the path at this distance. |
hit | Holds the properties of the resulting location. |
Return | bool True if terminated before reaching the position at maxDistance, false otherwise. |
Sample a position along the current path.
This function looks ahead a specified distance along the current path. Details of the mesh at that position are then returned in a NavMeshHit object. This could be used, for example, to check the type of surface that lies ahead before the character gets there - a character could raise his gun above his head if he is about to wade through water, say.
沿着当前路径取样一个坐标。
该方法会沿着当前路径检查指定的距离,如果取样到某一层上的点,会在NavMeshHit对象中返回该点网格的详细信息。 举个例子,这可以用于检查在角色到达目标点之前,前方是否存在某一物体。例如,如果角色打算涉水而过,它可以将枪举过头顶。那么这个方法就可以检测前方是否有水。
SetAreaCost(void)
public void SetAreaCost(int areaIndex, float areaCost);
Parameters | Description |
---|---|
areaIndex | Area cost. |
areaCost | New cost for the specified area index. |
Sets the cost for traversing over areas of the area type.
If you enable or disable the agent then the cost will be reset to the default layer cost.
设置穿过某一特定类型区域的代价。
如果你启用或禁用了agent,这个代价将会被重置为默认的层级代价。
SetDestination(bool)
public bool SetDestination(Vector3 target);
Parameters | Description |
---|---|
target | The target point to navigate to. |
Return | bool True if the destination was requested successfully, otherwise false. |
Sets or updates the destination thus triggering the calculation for a new path.
Note that the path may not become available until after a few frames later. While the path is being computed, pathPending will be true. If a valid path becomes available then the agent will resume movement.
设置或更新目的地从而触发新路径的计算。
这是最常用的方法,设置一个目的地然后让agent自动寻路。要注意的是,新计算出的路径在过几帧之后才有用。在路径被计算时,pathPending的值是true。在一个有效的路径变得可用后,agent会恢复移动。
这一点是需要注意的。新计算出的路径并不会使得agent直接去寻路,而是要经过几帧才会执行。因此最好是在找到路径过一会儿后再让agent去寻路。
SetPath(bool)
public bool SetPath(AI.NavMeshPath path);
Parameters | Description |
---|---|
path | New path to follow. |
Return | bool True if the path is succesfully assigned. |
Assign a new path to this agent.
If the path is succesfully assigned the agent will resume movement toward the new target. If the path cannot be assigned the path will be cleared (see ResetPath).
为agent分配一个新的路径。
该方法强制使agent走分配的路径。如果路径被成功分配之后,agent会恢复前往新目标的移动。如果路径不能被分配,那么它会被清除掉。
Warp(bool)
public bool Warp(Vector3 newPosition);
Parameters | Description |
---|---|
newPosition | New position to warp the agent to. |
Return | bool True if agent is successfully warped, otherwise false. |
Warps agent to the provided position.
Returns true if successful, otherwise returns false.
将agent直接放到提供的坐标处,可用于agent的瞬移。
1w7k字,好累啊嘤嘤嘤,帅气gg漂亮mm麻烦点个赞么么哒~~~