【Unity】Navigation system Navigation

1 Introduction

        New version of Unity navigation system. It can help us easily realize the navigation and movement effects of characters on the map. Compared with the old version, it feels almost the same, but the improvements in some places are really good.

2 Navigation installation

        The new version of the navigation system (Navigation) exists in the form of a package, so it needs to be installed in advance (menu bar-Window-PackageManager-search for package Navigation). As shown in the picture:

After the installation is complete, you can view the Navigation page from the upper menu page of the editor, as shown in the figure:

Navigation is the new version of the page, and Navigation (Obsolete) is the old version of the page.

3 simple cases

3.1 Map baking

        ​​​Create a ground Plane in the new scene, then add an empty parent object Map to it, and then add a NavMeshSurface component on the parent object. A Map parent object is added here to facilitate management. There is no mandatory child-parent relationship. For example, the NavMeshSurface component can also be added to the Plane.

After that, regardless of the meaning of its various parameters, click the Bake button directly to see that the map is baked and the navigation grid is displayed.

At the same time, we can see that in the Assets resource, a file with the same name as the scene has been created. There will also be an .asset resource file NavMesh-Map in the file. This file mainly records the various information we just baked.

At this time, if we no longer want the baking effect, we can directly click the Clear button on the NavMeshSurface component of the Map to clear the baking.

After clearing, the baking effect on the ground disappears, and the NavMesh-Map file just now is also deleted. At this point, a simple map baking operation is completed.

3.2 Role control

3.2.1 Improve the scenario

        ​ ​ ​ First, create a Sphere as our player (Player), and then create some Cubes as walls. We think that Cube is a wall, so it should be part of the map. To facilitate management, we set Cube as a sub-object of Map. Since we added a wall, the map has new content and we need to bake it again. Just click Bake again. The result is as shown in the figure. It can be seen that the ground around the wall is already an impassable area:

3.2.2 Perfect the role

        Next, we will add a Nav Mesh Agent component to our Player to cooperate with the baking of the map and prepare to achieve the effect we want.

Again, we don’t need to worry about the meaning of these parameters now. Let’s focus on implementing small cases first. Then create a Player.cs script to hang on the Player, and then add some code to achieve the Player's navigation effect.

Code:

using UnityEngine;
using UnityEngine.AI;

public class Player : MonoBehaviour
{
    //定义NavMeshAgent组件对象
    private NavMeshAgent agent;

    private void Awake()
    {
        //获取NavMeshAgent组件对象
        agent = this.GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        //实现效果:让Player导航移动到鼠标左键点击的位置。
        //若按下鼠标左键
        if(Input.GetMouseButton(0))
        {
            //向鼠标所在位置发送射线
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            //射线碰撞信息(用于接收信息)
            RaycastHit hit;
            //检测射线ray的碰撞,并将碰撞信息返回到hit中
            if (Physics.Raycast(ray, out hit))
            {
                //将射线碰撞点设置为Player导航的目的地
                //NavMeshAgent组件的应用
                agent.SetDestination(hit.point);
            }
        }
    }
}

At this point, the small case is completed. Run the program and click on the ground to see the navigation movement of the ball (Player).

3.3 Demonstration

4 component parameters

4.1 Nav Mesh Agent

This component is mainly mounted on the Player, that is, whoever wants to navigate and move will be mounted on it. In addition, objects mounted with NavMeshAgent will not be baked.

4.1.1 Agent Type

        The agent type can be understood as a group. Only Players, baked navigation grids, etc. in a group will affect each other. Humanoid is the default default, we click on this tab.

You can see that there is a settings option in the options. Click Open Agent Settings to open the settings panel.

We can modify the relevant parameters of Humanoid, or add a new Agent Type through the + and - buttons to customize the relevant parameters.

  • Name: The name of the created Agent Type.
  • Radius: The distance between the center of the Player and the wall or windowsill/the size of the baking area. For example, for a Cube on the map, if this is increased, the baked impassable area will become larger. See the picture and set the Radius to 0.5 and 1 respectively.

  • Height: The height of the Player/how low the Player can reach. Do you know the vehicle height limit pole? If it's too high, you can't get over it; if it's too low, you can't get over it.

  • Step Height: The maximum height of the steps (obstacles) that the Player can climb / the maximum height of the steps that can be baked. Set a certain height to bake to the ladder, as shown in the figure. In addition, Step Height<Height should be satisfied. In other words, no matter how high you set Step Height, as long as the Height is lower than you, the application height will be Height.

  • Max Slope: The maximum angle that the Player can climb the slope/the maximum angle of the slope that can be baked. As shown in the picture.

PS: Agent Type matching problem.

        Explain the use of custom Agent Types. If we add new Agent Types and replace them, then the Agent Types on the NavMeshAgent component of the Player and the NavMeshSurface component on the map must be replaced to keep them consistent, and the map must be re-baked. . As shown in the picture:

NavMeshAgent needs to have one or more corresponding NavMeshSurfaces, that is, the same Agent Type. We can also create multiple Players and Maps, then group them and assign them different Agent Types, so they will not affect each other. As shown in the picture, if you want to reproduce it, pay attention to the Collect Objects parameter that I modified so that the map only bakes itself and its child objects. This will be discussed later.

Generated Links

        Generate links. This refers to jump links.

  • Drop Height: Maximum drop height, that is, the maximum height for jumping from a high place.
  • Jump Distance: Maximum jump distance, that is, the maximum distance to jump from one point to another.

The above two parameters are basically used together, but how to use them specifically? First, find the NavMeshSurface component on our Map and check the parameter Generate Links. After checking, the above two parameters can be used to automatically generate jump links during baking. As shown in the picture:

4.1.2 Base Offset

        The deviation value is used to set the deviation, so whose deviation is it? First, let's observe the Player in the Scene window of the small case above.

You can see that there is a cylinder wrapping the ball on the outside. This cylinder is the real operating object in our navigation system. In other words, am I guiding the ball? I am navigating this cylinder, and the ball is just an accessory. Then our deviation value represents the height deviation between the "cylinder" and the "small ball". Note that it is the height.

PS: The cylinder was originally somewhat sunk into the ground. I have pulled the Player up as a whole here, but it does not affect it. Whether it is sunk into the ground, floating in the air, or running out of the map, as long as the distance is not too far, once Running will fall to the baked ground or be pulled to the edge of the map.

So let’s demonstrate the operation:

4.1.3 Steering

        Player control settings.

  • Speed: Indicates the player's moving speed, to be precise, it is the maximum speed, because it starts to increase slowly. In addition, when the speed is too high, it may move around the target point and be unable to accurately stop at the target point.
  • Angular Speed: Indicates the rotation speed of Player.
  • Acceleration: Player-like acceleration.
  • Stopping Distance: Stopping distance. Stop moving when a certain distance from the target point.
  • Auto Braking: Whether the Player automatically brakes when it is close to the target point. When the speed is too high, it may move back and forth around the destination point. This can prevent this. However, I tested it and found that it was useless (

4.1.4 Obstacle Avoidance

        Obstacle avoidance settings. What the parameters adjust is the "cylinder" we mentioned above, which also plays the role of obstacle avoidance.

  • Radius: avoidance radius. Cylinder radius. Spread radius from center.
  • Height: Avoidance height. Cylinder height. Raise the height upwards.
  • Quality: Avoid quality. The higher the quality, the more refined the avoidance.
  • Priority: avoidance priority. The range is 0-99, 0 is the highest priority, and 99 is the lowest priority. A Player with a high priority can knock back a Player with a low priority, but not otherwise. For example, when seizing the same target point, the one with higher priority can accurately reach the target point, while the one with lower priority will be blocked by the one with higher priority. As shown in the figure (at the beginning, the two Player priorities are the same and both are 50):

PS: Avoidance issue between Players of the same priority.

        If two Players move toward the same target point, avoidance will occur (this effect can be achieved by directly copying the Player in the above case. At this time, you can also try the priority test above). So what is the positional relationship between the target point and two Players with the same priority? Answer: It is based on the edge of the cylinder and is close to the target point on average. The expression may not be clear. Just look at the picture below. In the picture, the Radius of one Player is increased, and then both Players move towards the target point. From the picture, you can see that neither of the two small balls (Player) has reached the target. The position of the point is basically the tangent of the two small ball cylinders at the target point (although there is some deviation).

4.1.5 Path Finding

  • Auto Traverse Off Mesh Link: When checked, it means that the Agent can automatically pass the "jump link". If unchecked, it will stop when it reaches the edge of the jump point. It is valid for both Off Mesh Link and NavMeshLink jump link components. Also valid for jump links generated by Agent Type-Generated Links-Drop Height and Jump Distance parameters.
  • Auto Repath: When checked, it means that when the current path of the Agent is invalid, it can automatically calculate and find a new path to move forward. Take "jump link" as an example, uh... forget it, let's just look at the animation.

It should be noted that two paths should not be displayed at the same time, so that even if the other one is hidden, even if AutoRepath is not checked, the Player will find the other one; it is also necessary to complete the hiding of Route 1 and the display of Route 2 before the Player reaches the edge and stops, otherwise Even if checked, route 2 will not be found. Through these tests, we also roughly know what logic this RePath is.

  • Area Mask: An area where you can walk. Area is something similar to a hierarchy, which will be introduced later in the NavMeshSurface component. Only the area selected here is the area where Player can walk.

4.2 Nav Mesh Surface

This component is mainly mounted on the map. It is said to be a map. In fact, it can be basically any game object. It is usually mounted on an empty object, and then the game object that builds the map is placed in the child.

4.2.1 Agent Type

This is the same as Nav Mesh Agent, so I won’t go into details.

4.2.2 Default Area

        area. Something like a hierarchy. as follows:

By default, we are provided with three options: walkable, unwalkable, and jumpable. Of course, we can also click Open Area Settings to customize it ourselves.

I saw my old friend Agent again. Fill in the name in User to add our own area. Cost represents consumption, which can be understood as the priority judgment of which area the Player chooses to go to when facing multiple areas. We are all lazy people. Naturally, we don’t want to leave the area where the cost is greater. The same is true here. The area with the greater the cost has the lower priority. The smaller the cost, the greater the priority.

4.2.3 Generate Links

        If this option is checked, the collected objects will rely on the Drop Height parameter and Jump Distance parameter under the Generated Links of the Agent set in the Agent Type to generate "Jump Links (Link)". In other words, after checking, a "jump link" will be automatically generated with the help of the above two parameters during baking.
        In addition, this parameter can be overridden with the help of NavMeshModifier. Let’s talk about it later when this component is introduced.
        In addition... the jump link generated belongs to the Jump Area provided by default!

4.2.4 Use Geometry

        Use geometry. That is, what kind of geometry we use for baking, there are two options as follows:

  • Render Meshes: Render meshes.
  • Physics Colliders: Physics Colliders. I recommend this one, it has better performance.

4.2.5 Object Collection

        Object collection. The collected objects can only be baked during Bake.

Collect Objects: How to collect objects.

  • All Game Objects: Collect all game objects.
  • Volume: Set a 3D rectangular area to collect only objects in this area, or a part of the object, such as part of the ground, as shown in the figure:

  • Current Object Hierachy: Collects the object on which the current NavMeshSurface component is hung and all its sub-objects.
  • NavMeshModifier Component Only: Only objects with the NavMeshModifier component mounted will be collected.

PS: It should be noted that objects mounted with NavMeshAgent or NavMeshObstacle components will not be collected and baked.

Include Layers: Layer filtering when collecting objects. On the premise that the Collect Objects collection method is met, the collection objects are filtered hierarchically, and only objects belonging to the inclusion level can be collected.

4.2.6 Advanced

        advanced settings.

  • Override Voxel Size: Whether to override (set) Voxel Size.
  • Voxel Size: Set Voxel Size.

What is Voxel Size? The size of voxels. This affects the accuracy of the navigation mesh we generate by baking geometry. The appropriate size of voxels is the Radius 2-4 size of each Agent. The smaller the voxel size, the longer it takes to generate the navigation mesh.

  • Override Tile Size: Whether to override (set) Tile Size.
  • Tile Size: Set Tile Size.

What is Tile Size? Tile size(?), well just the size of blocks or something like that. This thing probably... means that when we re-bake, the changed area blocks, that is, the changes are divided by blocks, one block at a time. The smaller the value, the more detailed changes can be obtained, that is, the better the effect. Of course, the disadvantage is that more data will be generated and stored.

  • Minimum Region Area: Minimum region. With this parameter, small unconnected navmesh areas can be eliminated. Areas of the navmesh with a surface area smaller than the specified value will be removed. Note that some areas may not be deleted even if checked. The navigation grid is built in parallel in the form of block grids (Tiles above). If an area crosses the block boundary, it will not be removed. area. This is because region pruning occurs at a stage in the build process where surrounding blocks are inaccessible.
  • Build Height Mesh: Generate a more accurate height mesh for Nav Mesh Agent. When baking to generate the navigation mesh, you can find that the stairs actually form the navigation mesh in italics. This is because the navigation mesh is the approximate shape of the walkable space, which will flatten some features, so sometimes when we navigate The moved position will be inaccurate. In this case, you can check this to build a height grid. Note that building a height mesh will occupy memory and processing resources at runtime, and will increase the time it takes to bake and generate a navigation mesh.

4.2.7 Nav Mesh Data

        It is the data file generated after baking, as mentioned before. It’s gone after Clear, but it’s there after Bake.

4.3 NavMeshLink

This component is used to create "jump links" to enable Player to jump between different terrains. Generally, mounting it on an empty object will form something like a bridge. As shown in the picture:

4.3.1 Agent Type

Like the previous two components, there is no more introduction here. However, as before, the selection of Agent Type here needs to be consistent with Player and Map, otherwise it will not take effect.

4.3.2 Start Point&End Point

  • Start Point: The starting point, which is the starting position of the jump. Generally speaking, you can only jump from the starting position.
  • End Point: The end point, that is, the end position of the jump. Generally speaking, it is impossible to jump from this side.
  • Swap: Click to swap the starting point and end point.
  • Align Transform: Position the anchor point of the "jump link" to the center. As mentioned earlier, this script is usually mounted on an empty object. Then this empty object forms a bridge. Since it is an object, it has its own anchor point. By adjusting the Start Point and End Point, it is easy to adjust the anchor point. Point offset, this button is used to adjust the anchor point to the center. As shown in the picture:

4.3.3 Width

        Path width. The wider it is, the greater the range you can walk. As shown in the picture:

4.3.4 Cost Modifier

        Cost modification (overwriting/rewriting). First of all, as mentioned before, Area, like hierarchy, has priority, that is, Cost. Here, if it is a positive value, the Cost of this "jump link" is the value we entered, otherwise the Cost of the Area to which it belongs is used.

4.3.5 Auto Update Position

        Official website explanation: If this attribute is enabled, off-grid links will reconnect to the navigation grid when the endpoint moves. If disabled, the link will remain at its starting position even if the endpoint is moved.
        I feel that this is for the old component Off-Mesh Link. If the old component modifies the position of the two endpoints at runtime, the "jump link" will only follow when this option is checked. Endpoint adjustment. Now this new Link component, regardless of whether it is checked or not, can be adjusted with the endpoint at any time. It seems that it is not used.

4.3.6 Bidirectional

        Bidirectional. That is, you can jump no matter from the starting point or the end point!

4.3.7 Area Type

        Area type. It’s about setting up Area, which I’ve talked about before.

4.4 Nav Mesh Obstacle

Navigation mesh obstacle component. Whoever is an obstacle will be hung on. Player's movement will avoid obstacles. In addition, objects mounted with NavMeshObstacle components will not be baked.

4.4.1 Shape

        The shape of the obstacle geometry. It is divided into two types: Box (cube) and Capsule (capsule). No matter what the object we mount looks like, this option is the real geometric shape that acts as an obstacle, similar to a collision body.

4.4.2 Center

        The center position of the geometric shape.

4.4.3 Size

        The adjustable parameters are different when selecting Box and Capsule. This is very simple and I won’t go into details.

4.4.4 Carve

        Sculpture. When this option is checked, navmesh obstacles create a hole in the navmesh, i.e. digging out an untraversable area in the baked mesh. Three parameters will appear at the same time. These three parameters are used to adjust how the holes are re-carved when the navigation mesh obstacles move.

  • Move Threshold: When a navigation mesh obstacle moves farther than the value set by Move Threshold, Unity will treat it as a moving state. Use this property to set the threshold distance to update the moving sculpt.
  • Time To Stationary: The time (in seconds) to wait for the obstacle to be considered stationary.
  • Carve Only Stationary: When this property is enabled, obstacles will only be carved when stationary.

        Illustration of the difference between opening and closing:

A more detailed official explanation:

Obstacles and carvings

        Navigation mesh obstacles can affect the navigation of the navigation mesh agent (i.e. Player, the official documentation calls it an agent) in the game in two ways:

  • obstacle

        When Carve is not enabled, the default behavior of navmesh obstacles is similar to the behavior of colliders. Navigation mesh proxies try to avoid collisions with navmesh obstacles, and they will collide with navmesh obstacles when close. Obstacle avoidance behavior is very basic, with a short radius. Therefore, the navmesh agent may not be able to find its way in an environment where navmesh obstacles are cluttered. This mode is best used in situations where obstacles are constantly moving (for example, vehicles or player characters).

  • Sculpture

        When Carve is enabled, obstacles will carve a hole in the navigation mesh when they are stationary. When moving, obstacles are obstacles. After carving a hole in the navmesh, a pathfinder enables the navmesh agent to navigate around the location where the obstacle is carved, or to find another route if the current path is blocked by an obstacle. It's a good idea to turn on sculpting for navmesh obstacles (such as crates or barrels) that would normally impede navigation but can be moved by the player or other game events (such as explosions).

Official document pictures

(PS: If you use the obstacle method, you will be stuck in this situation. It means that it is more intelligent to find the path by carving on the navigation grid.)

Moving navmesh obstacle logic

        When the navigation mesh obstacle moves farther than the value set by Carve > Move Threshold, Unity will treat it as a moving state. When the navmesh obstruction moves, the sculpted holes also move. However, to reduce CPU overhead, the hole is only recalculated when necessary. The result of this calculation will be available in the next frame update. There are two options for recalculating logic:

  • Carve only when navmesh obstruction is stationary

        This is the default behavior. To enable this option, check the Carve Only Stationary checkbox of the Navigation Mesh Obstacles component. In this mode, sculpted holes will be removed when navmesh obstructions move. When a navmesh obstacle has stopped moving and has been stationary for longer than the Carving Time To Stationary setting, the obstacle is considered stationary and the carved holes are updated again. When a navmesh obstacle is moving, the navmesh agent uses collision avoidance to avoid it but does not plan a path around it.
        Carve Only Stationary is usually the best choice in terms of performance, and is a good option when the game objects associated with the navmesh obstacles are controlled by a physics system.

  • Carving after navmesh obstructions move

        ​​​​To enable this mode, uncheck the Carve Only Stationary checkbox of the navmesh obstacle component. With this checkbox unchecked, the carved holes will update when the obstacle moves further than the value set by the Carving Move Threshold. This mode is suitable for large, slow-moving obstacles (for example, tanks that infantry avoid).

        ​​​​Note: When using the navmesh query method, you should take into account that there is a one-frame delay between changing the navmesh obstruction and the change taking effect on the navmesh.

4.5 Nav Mesh Modifier

Navigation mesh modifier. You can adjust how specific game objects behave during navmesh baking. It's like making partial modifications to our Map. Modifiers affect the mounted object as well as its children.

        As shown below, Map is the parent object of all maps, and Other is the original map content. Here I added two pieces of ground, and added a parent empty object ModifierTest to them, and then mounted a Nav on its parent object. Mesh Modifier component. In this way, there are two pieces of ground in my map that can be modified by a navigation mesh modifier. The use will be demonstrated later.

4.5.1 Mode

        Modify the form. Divided into the following two types:

  • Add or Modify object: Add or modify an object. Indicates that our modifier can be used to perform modification operations.
  • Remove object: Remove the object. Indicates that our modifier can be used for removal operations.

So, how to use it?

Add or Modify object

        When you select Add or Modify object, there will be two more parameters below: Override Area (override area) and Override Generate Links (override jump link generation). These two rewritten contents have been introduced before in this article, and they are respectively checked as follows:

You can see that after checking, we can reselect the area to be set and whether to automatically generate Links.

        ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​OUT Out of the way, we must first turn off the automatic generation on the NavMeshSurface component of the Map, and then we can rewrite the two pieces of ground to generate them. as follows:

You can see that only those two floors have jump links generated. PS: Although the jump link is linked to the large ground on the left, the setting is that only the two pieces of ground controlled by the modifier can be generated, so the Player can move from the two pieces of ground to the big ground, but cannot move from the big ground to the small ground. .

        Then demonstrate Area. First, we turn off the Override Area baking of the modifier. The default baking is Walkable, then use the modifier to change the Area of ​​the two grounds to Jump, and then bake. as follows:

You can see that the colors of the two pieces of ground have changed, and the Area has been rewritten.

Remove object

        This is very simple. Selecting this means that the objects affected by the modifier will be completely removed from baking.

4.5.2 Affected Agents

        Agents affected. It is the one in Agent Type. For example, if the Type set by NavMeshSurface is A and the modifier is B, then the modifier will not work unless it is changed to A. Demo:

4.5.3 Apply To Chilren

        Whether it applies to children. As mentioned earlier, the modifier affects the mounted object and its sub-objects. Here it is decided whether to affect the sub-objects.

4.5.4 Modifier of child and parent levels

        When the Modifier component is hung on both the child and the parent, what is their priority relationship? The answer is an overwriting relationship, where the child covers the parent. But pay attention to what is covered here. Is it the modifier? No, what is covered is our game object, that is, it is not a simple modifier replacement, but the final modification result of the multi-layer modifier must be determined based on the parameters of the modifier. It will be easier to understand after understanding this.
        Add an empty object parent F to ModifierTest, mount a Modifier component, and then.... Look at the picture, the component settings on F and ModifierTest are like this.

So what is the result of baking? The answer is that the two floors are not baked. So what if you uncheck Apply To Children in ModifierTest? The answer is two-ground baking. Check out the demo:

Because after we remove the check box, the child level modifier will not act on the child, so the two floors cannot be modified. However, at this time, it should be noted that not being able to modify it does not mean that it is baked by default. We also have a modifier on the upper layer, the child level. If less than two floors are modified, the parent's modifications to the two floors will not be overwritten by the child's modifications, so the result is the modification result of the parent modifier.

4.6 Nav Mesh Modifier Volume

Navigation mesh modifier volume. Used to use a Box to calibrate an area, that is, set a certain area to an Area (similar to the hierarchical one). There will be a demonstration later.

4.6.1 Size

        Box size, you can also click the Edit button to edit directly, similar to the collision body.

4.6.2 Center

        The center of the Box.

4.6.3 Area Type

        You want to modify the Area marked as. Demo:

Pay attention to the height of the Box. It must hit the baked ground. Finally, after I raised the Box, the ground area could not be marked.

4.6.4 Affected Agents

        The affected Agent is the one whose Agent Type is set.

5 Conclusion

        ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​   It took a long time to take notes... Anyway, it's okay, at least I won't be afraid of forgetting later. That’s pretty much the content of the navigation system, so let’s end it here.

Guess you like

Origin blog.csdn.net/Davidorzs/article/details/134602222