UE4 AI入门(一)

评论0 1.9k浏览


相比较之前的WIKI系列AI视频(链接:http://www.unrealchina.net/forum ... 3968&extra=page%3D1),本文更简单理解,而且使用的是最新版本的引擎,所以大家放心食用吧


Behavior Tree Quick Start Guide
The Behavior Tree Quick Start Guide walks you through the process ofcreating a NavMesh, creating an AI Controller, creating a Character that willbe controlled by that AI Controller, and creating all the parts necessary for asimple Behavior Tree.
这一节将带你创建NavMeshAI Controller、被AI Controller控制的Character,创建一个行为树的所有必要的部分
1. Essential Setup
This Quick Startmakes some assumptions(假设) about what isavailable in the project, as such, if you aren't comfortable making substationsor problem solving on the fly, then you should setup the project as follows.
1.  Open Unreal Editor
2.  Generate a new project based onthe Blueprint Top Down template
The StarterAssets are optional for this quick start guide.
If you needfurther explanation of starting a new project, see the Project Browser UserGuide.
基于Blueprint Top Down创建工程

2. Create a Nav Mesh Bounds Volume 创建NavMesh边界

The NavMesh inUnreal has a number of functions that work well with Behavior Trees, and whileit may not be necessary depending on the game you are making, it will help in anumber of game types. Also, the Top Down template already includes a Nav MeshBounds Volume, but you may choose to start in a completely blank project at alater date.
虚幻四中的NavMesh 配合行为树使用有很多作用,也许在你自己创建的游戏里面用不到,但是大部分游戏类型还是用的到的。虽然Top Down模板里面已经有了Nav的边界,但是当你有了经验以后你可以从一个完全空白的工程开始。
1.  Modes Panel                                Create   Volumes.
2.  Click and drag a Nav Mesh BoundsVolume into the map.
3.  Translate and scale the volume so itencapsulates(封装) the areas youwant your characters to be able to navigate. 调整边界大小,把你需要的区域封装起来
o  You can use morethan one Volume if you like, or one large one that encapsulates the entirelevel.
4.  While working in the Viewport, press the"P" key to see if your NavMesh is building.
If you see agreen mesh overlay on your floors, it is building correctly. When the meshturns red, it means it is recalculating a section(区域) because you either moved the volume orthe mesh inside of it.
You can pressthe "P" key at any time to show or hide the NavMesh.
3. Create theBasic Assets 创建基本的资源
To start, youwill need create 4 assets in the Content Browser: An AI ControllerBlueprint, A Character Blueprint, and Behavior Tree Asset, and a Black BoardAsset.
需要创建4个资源:AI Controller蓝图、Character角色蓝图、行为树、黑板资源。
1.  New -> Blueprint -> AIController  
You will need tosearch for AI Controller, as they are different from Player Controller.
AI Controller的父类为AI Controller,他和角色的Controller不同。
Name this Blueprint Follower_AI_CON命名为Follower_AI_CON
2.  New -> Blueprint -> Character创建角色蓝图
Name this Blueprint AI_Character.
3.  New -> Miscellaneous -> BehaviorTree
Name the BehaviorTree FollowerBT.
4.  New -> Miscellaneous -> Blackboard.
Name the Blackboard FollowerBlackboard.
4. Setup theCharacter Blueprint 设置角色蓝图
As we havecreated a project with a Character already in it, we haveaccess to a humanoid Skeletal Mesh and its AnimationBlueprint. We will use these in the tutorial, but feel free to use your ownif you have them available.
This Characterwill become our new AI Character. The reason we use a Character, over say aPawn, is to gain access to the Character Movement Component's functionality.
1.  Double-click theAI_Character Blueprint in the Content Browser to open it forediting.
2.  Select the Mesh componentin the Components panel.
3.  In the Details panel,find the Mesh category and assign the HeroTPP (or yourown) Skeletal Mesh.
在详细面板中,给骨骼网格组件赋值HeroTPP 或者你的骨骼网格
4.  Move the Mesh Componentto center it up inside in the capsule.
5.  Rotate the Mesh Componentso it faces the direction the blue Arrow Component is pointing.
6.  In the Details panel,find the Animation category and assign the HeroTPP_AnimBlueprint tothe Animation Blueprint Generated Classproperty.
7.  Select the CapsuleComponent fromthe Components panel, then in the Details panel,adjust the Capsule Half Height and Capsule Radiussothey encompass the Skeletal Mesh.
8.  Select the Character Movement Component.
9.  In the Details panel,in the Movement Component category, adjust the Agent Radius and Agent Heightvalues.
在详细面板,调整角色移动组件的Agent 代半径和代高度。
Set the AgentRadius to at least the Capsule's radius, and the Agent Height to at least twicethe Capsule's "half height."
10. With theCharacter Movement Component still selected, change the Max Walk Speed property,in the Character Movement category to400.
11. Click the ClassDefaults   button and assign the new AI Controller (Follower_AI_CON) to the AIControllerClass property in the Pawn category.
选中类默认,在Pawn目录下为AIController 赋值为我们刚刚创建的Follower_AI_CON
12. Compile   and Save  
5. Setup the Blackboard Asset 设置黑板资源
The Blackboard assetstores all of the data needed for a specific(具体) instance of an AI controller that willbe referenced by the Behavior Tree. In this specific case, we'll bestoring an Actor to Follow (TargetToFollow), the AI's starting location(HomeLocation), and the last know location of the Actor we're following (TargetLocation).黑板资源存储着行为树中引用的具体事例所需要的数据。在接下来这个特定的例子中,我们需要存储一个用来跟随的物体,AI起始的位置,和目标物体三个数据。
5.  Double-click theBlackboard asset in the Content Browser. 双击进入黑板资源。
6.  Using the New Key button  , add an Object value named TargetToFollow.
7.  Add a Vector value named HomeLocation.
8.  Add a Vector valuenamed TargetLocation.
9.  Save your Blackboard asset.
6. Setup the AI Controller Blueprint 设置AIController蓝图
Using the Top Downtemplate gives us access to mouse controls to move our character around, butfor the other character we are going to create, he will need his owncontroller. This AI Controller is going to set a few values on its Blackboardand is going to kick off the running of our Behavior Tree. For those familiarwith Blueprints, here is what the final Event Graph will looklike:
Below are thesteps for creating the first part of the Event Graph. Step 7.AI Controller Blueprint: Initial Blackboard Values and Step 8.AI Controller Blueprint: Run the Behavior Tree also involve editingthis graph.
1.   Double-click the AI ControllerBlueprint in the Content Browser to begin editing it.
2.   Usingthe Right-click Context menu in the Graph Panel:
1.   Add an EventBegin Play node.
2.   Add an UseBlackboard node.
添加Use Blackboard节点。
3.   On the UseBlackboard node, change the Blackboard Asset to theone you created in step
3. 制定UseBlackboard节点中的Blackboard资源。
4.   Connect theoutput execution pin on the Event Begin Play node, to theinput execution pin on the Use Blackboard node.
In the nextstep we'll continuing editing this graph and setup the initial Blackboardvalues for our AI Controller.
7. AI Controller Blueprint: InitialBlackboard Values AIController蓝图:初始化黑板
Now we need toset the "HomeLocation" key on the Blackboard. This is amore involved step.
5.   You needa Get Blackboard node and a Get Controlled Pawn node.
需要 GetBlackboard Get Controlled Pawn 两个节点。
6.   Get a Referenceto Self node from the Right-click context menu andconnect it to the Get Blackboard node.
添加一个 Reference to Self 节点,如图连接。
7.   Drag offthe Return Value of the Get Blackboard node,search for "Vector", and create a Set Value as Vector node.
如图创建Set Value as Vector 节点。
8.   Drag offthe Return Value of the Get Controlled Pawn nodeand create a Get Actor Location node.
如图连接 Get Controlled Pawn  Get Actor Location节点。
9.   Connectthe Return Value pin of the Get Actor Location nodeto the Vector Value pin of the Set Value as Vector node.
10. Drag off KeyName on the Set Value as Vector node and use Promoteto Variable from the context menu.
11. The variableshould be awaiting a name in the My Blueprint panel, name thevariable to HomeLocation.
§  If you clickedanywhere before naming the variable, you can rename it in the MyBlueprint panel using the Right-click context menu.
12. Compile theBlueprint  
13. Selectthe HomeLocationKey variable in the My Blueprint Panel.
在左边的MyBlueprint面板中选择HomeLocationKey 变量。
14. In the Details panel,change its Default Value to the exact name of the Vector Valueon the Blackboard, in this case, HomeLocation
15. Connect theoutput execution pin of the Use Blackboard node to the inputexecution pin of the Set Value as Vector node.
In the nextstep we'll continue editing this graphs and add to this graph to make the AIController run the desired Behavior Tree.
8. Controller Blueprint: Run theBehavior Tree 在Contoller蓝图中运行行为树
Finally, wejust have to run our Behavior Tree with a single node.
16. Create a RunBehavior Tree node.
创建RunBehaviorTree 节点。
17. Set theBTAsset value to the Behavior Tree asset you created in step3.
18. Connect theoutput execution pin of the Set Value as Vector node to theinput execution pin of the Run Behavior Tree node.
19. Save your AIController Blueprint.
9. Place the Character 放置AI角色
We need toplace our AI_Character into the level so it can interact with the player orenvironment.
Steps 步骤
§  From the ContentBrowser, click and drag the AI_Character, that youcreated earlier, into the level.
10. Behavior Tree Basics 行为树基本信息
The Root nodestarts the tree, and all other nodes connect below it.
It can onlyhave one output connection. The darker bar on the bottom of the node is like apin in Blueprint that you can drag off to connect to other nodes:
However,unlike Blueprint node pins which allow you to drag connections from eitheroutput to input, or input to output, Behavior Tree nodes are directional: youmust drag from an "output bar" to an "input bar."
Steps 步骤
21. Open yourBehavior Tree asset, if it is not open already, by Double-clicking itin the Content Browser.
22. In BehaviorTree mode, Right-click in the graph area and create two Composites -> Selector nodes.
右键添加两个选择器Selector节点: Composites -> Selector
23. In BehaviorTree mode, Right-click in the graph area and create a Composites -> Sequence node.
右键添加一个序列Sequence 节点:Composites -> Sequence
These are the2 primary decision making nodes available for Behavior Trees. The Selector nodewill run through its children, from left to right, until one of them succeeds,at which point it will fail back up the tree. While the Sequence nodewill run through its children from left to right until one of them fails,at which point it will fail back up the tree.
在行为树中有两个主要的决策制作的节点可用。选择器Selector 节点的执行顺序是:从它的子节点最左边开始向右执行,知道有一个节点成功执行完,就停止执行,返回到行为树。而顺序Sequence节点也是子节点从左向右执行,但是当他们其中一个节点失败了,就停止执行,返回到行为树。
While Selectorand Sequence nodes will have a number of children under them, the Root nodecan only have one node attached to it.
顺序Selector 和序列Sequence 节点都可以有多个子节点,而根节点只能有一个连接的子节点。
11. Make a Service 制作一个行为树服务
Services attachto Composite (混合)nodes, andwill execute at their defined frequency as long as their branch is beingexecuted. These are often used to make checks and to update the Blackboard.These take the place of traditional Parallel nodes in other Behavior Treesystems。
行为树的服务是添加到混合类节点 Composite:共有三种类型的混合节点:选择Selector、序列Sequence、简单平行节点Simple Parallel节点。下一篇文章就有介绍了)只要他们的分支开始执行时服务就会按照他们比定义的频率来执行。服务通常是用来判断和不断更新行为树的。它取代了其他行为树系统里面的传统的平行节点。
In this case,the service is going to look for any Pawn that is not an AICharacter, then set the TargetToFollow and TargetLocation Blackboard keys.
24. Open theFollowerBT Behavior Tree by Double-clicking it in the ContentBrowser.
25. Click NewService   button.
It will createin the same folder as the Behavior Tree.
26. Rename it inthe Content Browser to "AgroCheck".
27. The editorshould have already opened it for editing, but if not, Double-click itin the Content Browser.
28. Create thefollowing graph:
Click theimage to expand it, or click here to openit in the window.
The variablenames, types, and values for this Blueprint:
Thevariable DesiredObjectTypes is an Array of the type EObjectTypeQuery with asingle element set to Pawn. To do this, select theDesiredObjectTypes variablein the My Blueprint panel, then in the Details Panel, under the Default Valuecategory, click the  button to add an element. Using the pull down on that element,select Pawn.
If the DefaultValues category doesn't show anything, Compile the Blueprint.
Here is whatis going on in this graph:
29. Event Tick worksjust like the same even in Actors, except it is ticked at a rate defined in theBehavior Tree.
30. The OtherActor passed in is always the Controller calling the Behavior Tree, solet us store that. But, only do that if we don't already have it stored, justto reduce some overhead from the cast node.
OwnerActor 就是调用行为树的Controller,所以当我们还没有给AI_Con_Ref赋值的时候,就要把它保存成AI_Con_Ref
31. Do a MultiSphere Trace for Objects based on the location of the controlled pawn, and getall the pawns, minus the controlled pawn.
32. The ForEach loop then figures out if the player was hit.
33. If it is, do avisibility trace to see if our AI pawn can see the player pawn.
如果碰撞到的话,做射线检测,判断AI 与玩家之间是不是有其他物体,AI能不能看到玩家。
34. If yes, setthe appropriate values on the blackboard object for the AI pawn (Target toFollow and Target Location).
如果是的话,就为AI 角色更新黑板值参数。
35. If no, clearthe Target to Follow key on the blackboard.
12. Make a Task  制作一个行为树任务
Tasks arenodes that "do" things, like move an AI, or adjust Blackboard values.They can have Decorators attachedto them.
任务Tasks 是一些做事情的节点,比如移动AI,或者调整黑板值。他们可以附加装饰器。
This Task isbasically a re-creation of the Move To node, with one majordifference: this Task will have the AI always run towards the Player's Pawn,instead of its location. Also, it helps to break things down and see that ifyou don't ever execute Finish Execute the Task Node willcontinue to process, and the AI MoveTo node shows thisperfectly.
任务Tasks 是对MoveTo节点的重写,有一个明显的不同:任务总是让AI想着PlayerPawn物体方向跑动,而不是它的位置。并且它也可以用来停下来判断,如果还没执行到FinishExecute节点,任务会继续执行。AI Move To 节点很好的展示了这一点。
36. Open theFollowerBT Behavior Tree by Double-clicking it in the ContentBrowser.
37. Click NewTask   button.
It will createin the same folder as the Behavior Tree.
38. Rename it inthe Content Browser to "RapidMoveTo".
39. The editorshould have already opened it for editing, but if not, Double-click itin the Content Browser.
40. Create thefollowing graph:
Click theimage to expand it, or click here to openit in the window.
The variablenames, types, and values for this Blueprint:
Here is whatis going on in this graph:
41. The EventReceive Execute is the event that is called when the Behavior Treeruns this task node.
当行为树运行一个任务是会调用任务的 Event Receive Execute节点。
42. We store theFollower_AI_CON like we did in the previous step.
存储Follower_AI_CON 值。
43. The Castto Actor node pulls the "TargetToFollow" object value fromthe Blackboard and casts it to an Actor so we can use it in the AIMoveTonode.
强制转换,这样就可以在AI Move To 中使用TargetToFollow
44. On success,the task will run the Finish Execute node successfully.
AI Move To 成功,任务就会成功运行FinishExecute节点。
13. Make a Decorator  制作一个任务装饰器
Decorators, also knownas conditionals in other Behavior Tree systems, are attached to either a Composite ora Task node anddefine whether or not a branch in the tree, or a single node, can be executed.
This Decorator isgoing to stop execution of the Rapid Move To branch of the Behavior Tree oncethe AI's Pawn is close enough to its target. While this could be handled inthe Rapid Move To Task or by just using a Move To Task,this decorator can take in any Actor and can block execution of any branch.This makes it reusable in a number of situations.
0.   Open theFollowerBT Behavior Tree by Double-clicking it in the ContentBrowser.
1.   Click NewDecorator   button.
It will createin the same folder as the Behavior Tree.
2.   Rename it inthe Content Browser to "CloseEnough".
3.   The editorshould have already opened it for editing, but if not, Double-click itin the Content Browser.
4.   In theFunctions section of the My Blueprint Tab, "Override" PerformConditionCheck.
5.   Create thefollowing graph in that new function:
Click theimage to expand it, or click here to openit in the window.
The variablenames, types, and values for this Blueprint:
As this is aFunction Graph, if you use the Code Snippet from the graphimage above, you will only get the center portion of the graph, and thebeginning and end nodes will not be connected. Just wire those connects as theimage shows, and it will work just fine.
6.   Event ReceiveCondition Check is the event sent to this Blueprint when the BehaviorTree hits a node with this condition on it.
7.   Once again,store the AI Controller so we can reference it later easily.
8.   Get the Actorwe want to follow (the Player Pawn).
9.   Get thedistance between that Actor and the AI Pawn.
10. If distance isgreater than a configurable amount, then the condition returns True.If not, then it returns False and blocks execution of theportion of the Behavior tree it is on.
This will makeit so the Behavior Tree is not constantly cycling to the RapidMoveTo andback out again. Basically, if he caught up to the player, then stop.
         如果这个距离比我们定义的要大,那么将会返回真,否则将会返回假,并且停止执行行为树上的相关代码段。这样写会防止行为树重复的调用回收RapidMoveTo 任务。简单来说就是,当AI靠近了玩家,就停止。
14. Build the Behavior Tree  构建行为树。
You should nowhave all the pieces needed to build this Behavior Tree:
Let's breakdown what's going on.
§  The AI willjust stand around if it hasn't detected a Pawn that isn't an AI Character.
§  The AgroCheckService is constantly looking for a suitable target.
§  Once it findsone, the left most branch is open, and the AI runs towards the targeted Pawn.
§  Once it getsin range of that Pawn the branch is prevented from executing, thusly returningit to the top of the graph
§  If the desiredPawn hides, then the right most branch will be able to run, which causes the AIto move to the last know location of the desired Pawn.
§  Once there, itwaits, then returns home.
§  At any time,if a suitable target is found, the right most branch will be forced to stopexecuting, and the left most branch will be opened.
Let us stepthrough the creation of this tree.
Basic Setup 基本的设置
You may havealready done this back in part 8 of this guide, but just in case you did notsave those changes, here are the steps for creating the basic structure of the BehaviorTree:
18. If theBehavior Tree is not open for editing, Double-click it inthe Content Browser to open it for editing.
19. Switch toBehavior Tree Mode
20. When you firstedit a Behavior Tree, it will only have the Root Node:
21. You can Right-click inthe Graph Editor to create nodes
1.   Add a Composites -> Sequence Node.
添加一个序列Sequence 节点
2.   Add two(2) Composites -> Selector Nodes.
22. Connect theRoot Node to one of the Selector Nodes
23. Connect thenewly connected Sequence Node to the Selector Node and the other Sequence Node.Then arrange them like so:
2nd SelectorNode on the left, Sequence Node on the right.
Add the Service 添加服务
24. Usingthe Right-click context menu on the top selector node, adda Services -> Agro Check Node.
25. Selectthe Agro Check box on the Selector Node, andusing the Details panel, set the Target to Follow propertyto TargetToFollow, set Target Location to TargetLocation, adjustthe Interval to 0.5 andthe Random Deviation to 0.0
点击服务,在详细面板中,设置Target to Follow变量为TargetToFollowTarget LocationTargetLocation,设置Interval (间隔)为0.5Random Deviation(偏差)为0.
Add the Tasks 添加任务
26. Right-click in theGraph area to bring up the context menu, and add the 4 Tasks:1 Rapid Move To Node, 1 Wait Node, and 2 MoveTo Nodes:
27. Connect thelower Selector Node to the Rapid Move To Node.
28. Connect theSequence node to the Move To Nodes, and the Wait Node.
29. Arrange thenodes like so:
From left toright: Rapid Move ToMove ToWaitMoveTo.
从左到右分别是:Rapid Move ToMove ToWaitMoveTo.
30. Select theleft-most Move To Node, and using the Details Panel,set the Blackboard Key property on the to TargetLocation
31. Set the BlackboardKey property on the right-most Move To Node to HomeLocation
32. Selectthe Wait Node, and using the Details panel,set its Wait Time property to 2.5
33. Selectthe RapidMoveTo node, and using the Details panel,set its Target to Follow property to TargetToFollow.
选中RapidMoveTo节点,设置Target to FollowTargetToFollow
Add the Decorators 添加装饰器
34. Right-click thelower Selector node and select Add Decorators.. -> Blackboard .
35. Right-click thelower Selector node and select Add Decorators.. -> CloseEnough.
右键选择下面的Selector节点,添加装饰器:Close Enough.
36. Set the ObserverAborts property on the Blackboard decorator to Both, KeyQuery to Is Set, andthe Blackboard Key toTargetToFollow
选中黑板装饰器,在详细面板中,观察者终止选项选择BothKey Query  Is SetBlackboard Key TargetToFollow
37. Set the AcceptableDistance property on the Close Enough decoratorto 100.0, and Target to Follow propertyto TargetToFollow.
选中CloseEnouge装饰器,设置Acceptable Distance100.0Target to Follow TargetToFollow.
38. Right-click the Sequence nodeand select Add Decorators.. -> Blackboard.
39. Right-click the Sequence nodeand select Add Decorators.. -> Reached Move Goal.
40. Right-click the Sequence nodeand select Add Decorators.. -> Blackboard.
右键选中序列节点,依次添加三个装饰器:BlackboardReached Move Goal.Blackboard
After addingall those decorators, the full node block should look like this:
41. On thefirst Blackboard decorator, set the Key Query to Is Not Set, andthe Blackboard Key to TargetToFollow
对于第一个黑板装饰器,Key Query Is Not Set,Blackboard Key  TargetToFollow
42. On thesecond Blackboard decorator, set the Key Query to Is Set, andthe Blackboard Key to TargetLocation
对于第二个黑板装饰器,Key Query Is Not Set,Blackboard Key  TargetLocation
43. On the ReachedMove Goal decorator, enable the Inverse Condition property.
After settingthose properties, the full node block should look like this:
And that isit! Leave the Behavior Tree editor open while using Playin Editor and you will be able to see how the tree is operating. Ifyou get close enough to the AI and it has line of sight to you, it will beginto chase you. If you are able to break line of sight, he will go to your lastknown location, wait, then return to where he started.

1.jpg (439.99 KB, 下载次数: 9)