Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

AI: Behaviour trees in Unity: Behave 1.1 released

Discussion in 'Assets and Asset Store' started by AngryAnt, Sep 29, 2010.

  1. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    This thread is primarily for Behave announcements and 1.x support. For Behave 2 support, please use your AngryAnt community account - available through the Help menu when Behave 2 is installed.

    Update 12:
    Whoops - missed an update!

    Behave 2.4 is now out, adding utility and blackboard methods to the offering: http://angryant.com/2014/11/28/Behave-2-4/

    Update 11:
    Behave 2.2 is out!

    http://angryant.com/2013/12/23/Behave-2-2/

    Update 10:
    Behave 2.1 is out!

    http://angryant.com/2013/10/06/Behave-2-1/

    Update 9:
    Behave 2 is out!

    http://angryant.com/2013/08/25/Behave-2-0/

    Update 8:
    Whoop! Sorry about my long absence from this thread. Been a bit busy. But now Behave 1.4 is here! Blogpost contents:

    So obviously I ended up not spending more time on that RPG thing... I did however work on some 3.5 stuff back at Unity, some upcoming demo stuff and baby Lili was born.

    Meanwhile I spent spare time on Behave rather than the RPG thing, so now 1.4 is ready for release. TADAA!

    This release primarily holds runtime optimizations, fixes and tweaks. Specifically I would like to highlight the ability to mark components as "instant". The instant flag affects sequences and selectors when moving between child nodes. When an instant child component completes, rather than waiting for the next tick to tick the following child node, the sequence or selector does it immediately.

    Anywho, get it on the asset store and remember to rebuild your libraries after installing.

    The rest of the changes follow:

    1.4:
    - Fixed decorator incorrectly initializing on every returning tick when tick handler returned Running.
    - Fixed debugger view dependency on active tree editor - causing reported null reference exception.
    - Fixed missing scrollbars on browser window.
    - Reduced logging noise from debug builds.
    - Agent blueprints can now be MonoBehaviour based.
    - Clarified wording on "library not loaded".
    - Now handling reset a bit cleverer - potential performance boost.
    - Changed the default success criteria of Parallel components from SuccessOrFailure to Success.
    - Added "instant" flag to components. Components marked instant will affect sequences and selectors when moving between child nodes. When a child node marked "instant" completes, rather than waiting for the next tree tick to tick the following child node, the sequence or selector does it immediately.
    - The compiler progress bar returns.
    - Editing a Behave asset now focuses the asset browser last instead of the tree editor.
    - Behave can now be installed in any subfolder of Assets - provided its internal folder structure remains intact.
    - Compilation speed improvements.
    - Enabled references across collection borders.
    - Added Tree.DataSize - returning the number of bytes used by a tree instance. This is also displayed in the debugger window.

    You'll find a link to the package in the download section. Have fun!

    Blog post.

    Update 7:
    After quite a long break (including shifting around at utech, doing a Path release etc.), Behave is finally getting another update!

    This release is primarily a bugfix and editor polish release. One thing I'd like to highlight though is the addition of agent blueprints. From the changelog:

    Generally this enables you to more explicitly tie up handlers and cuts down on tree initialization time. Oh and of-course you gain auto-completion when setting up your handlers.

    Anyway, here's the whole changelog:

    1.3:
    - Fixed priority selector init flag resetting.
    - Fixed reference handling on tree renaming and deletion.
    - Fixed references still pointing at old collection post collection duplication.
    - Fixed compilation of actions and decorators with non-integral float parameters.
    - Fixed GUI list behaviours.
    - Fixed passing context back and forth between referenced trees and referrer.
    - Fixed reordering connections not causing save state to be set.
    - Various GUI tweaks.
    - Runtime optimisations.
    - Enabled scrolling of the tree list in the debugger window.
    - Exposed Tree.ReflectForwards.
    - Added Tree.ResetForwards.
    - Added agent blueprints - connecting to agent handlers through virtual methods rather than reflected handlers.
    - Made connections selectable in the tree editor via the connection nub.
    - Moved connection managing from the inspector to the tree editor, where it is more visible and handy.
    - Added support for disabling connections - for faster, less destructive debugging.
    - Double-click reference component to jump to referenced tree.
    - Changed "Cannot update unregistered tree" handling from an exception to an error message. Still need more info.
    - Now showing string and float parameters in the tree editor if either is set.</pre>

    You'll find a link to the package in the download section. Have fun!

    Blog post.

    Update 6:
    I just updated the Behave documentation to include a link to Bjoern Knafla's very nice introduction to behaviour trees, published for #AltDevBlogADay.

    http://angryant.com/behave/documentation/

    Update 5:
    I've set up a survey to better understand peoples use of Behave and uncovered needs. Please take a few minutes to complete the survey and help shape future releases of Behave:

    http://angryant.com/behave/survey/.

    Update 4:
    Just set up the Behave release project on github. Please use the github issue tracking system for bug reports and feature requests.

    http://github.com/AngryAnt/Behave-release

    Update 3:
    Just finished uploading Behave 1.2. A few fixes in there including one for the broken release build. Also some additions: Priority selectors (thanks Jiong for pushing that up my TODO list again) and branch contexts.

    Blog post:
    http://angryant.com/2010/10/11/behave-1-2-released/

    Changelist:

    - Fixed release building.
    - Added the priority selector, introducing the API points:
    - int IAgent.SelectTopPriority (Tree sender, params int[] IDs);
    - enum BL[LibraryName].PriorityType { PriorityName, ..., Unknown };​
    - Added support for branch contexts, introducing the API points:
    - enum BL[LibraryName].ContextType { ContextName, ..., Unknown };
    - int Tree.ActiveContext { get; }​
    - Changed IAgent interface:
    - Tick (bool init, Tree sender) -> Tick (Tree sender, bool init)​
    - Added "Select asset" button to the standard inspector.
    - Interface polish.


    Update 2:
    Added a new video demonstrating how to get from an empty project to up and running with Behave plus brief introduction to the authoring environment:
    http://angryant.com/2010/09/29/video-behave-starting-from-scratch/

    Update:
    The new runtime is now documented on AngryAnt.com - I will be adding documentation for the authoring environment soon.
    http://angryant.com/2010/09/29/behave-runtime-documentation-updated/

    Original post:
    That's right. I'm ready with a new version of Behave - fully Unity 3 compatible, stuffed with polish and a shiny new debugger.

    Blog post:
    http://angryant.com/2010/09/29/behave-1-1-released/

    Debugger teaser:
    http://angryant.com/Debugger.mov

    Changelist:

    - Made compatible with Unity 3.0 - including ensuring that the 2.5-2.6.1 bug preventing compilation on Windows is fixed on the Unity side.
    - UI tweaks and polish.
    - Added the option to have return values of nodes be inverted.
    - Fixed compiler bug when facing sequence or selector with only one child node.
    - Renamed Library.Tree -> Library.InstantiateTree.
    - Added Tree.Tick () and Tree.Reset () methods using the IAgent instance given at instantiation of the tree.
    - Removed the abstract Library class.
    - Changed generated library class:
    - Trees -> TreeType.
    - Actions -> ActionType.
    - Decorators -> DecoratorType.
    - Tree InstantiateTree (int, IAgent) -> static Tree InstantiateTree (TreeType, IAgent)
    - int TreeID (Tree) -> static TreeType Type (Tree)
    - bool IsAction (int) -> static bool IsAction (int)
    - bool IsDecorator (int) -> static bool IsDecorator (int)​
    - Upped editor performance.
    - New asset structure change with automatic import of Behave 1.0 assets.
    - Changed action and decorator handlers. These are now the handlers mapped:
    - public BehaveResult Init[Name][Action/Decorator] (Tree sender, string stringParameter, float floatParameter, IAgent agent, object data);
    - public BehaveResult Tick[Name][Action/Decorator] (Tree sender, string stringParameter, float floatParameter, IAgent agent, object data);
    - public void Reset[Name][Action/Decorator] (Tree sender, string stringParameter, float floatParameter, IAgent agent, object data);
    - public BehaveResult Init[Name][Action/Decorator] (Tree sender);
    - public BehaveResult Tick[Name][Action/Decorator] (Tree sender);
    - public void Reset[Name][Action/Decorator] (Tree sender);
    - public BehaveResult [Name][Action/Decorator] {get; set;}​
    - Added support for collection duplication.
    - Moved debug rendering into the editor with its own dedicated debugger window, including actor listing.
    - Debugger now renders active sub-trees as well.
     
    Last edited: Nov 29, 2014
  2. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    Very sweet, thank you for the update :)


    With the update of mono in unity, does it still rely on a distinct mono installation?
     
  3. maxfax2009

    maxfax2009

    Joined:
    Feb 4, 2009
    Posts:
    410
    Hi Dreamora

    I dont think so from reading Behave download page:

     
  4. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    thats why I ask, because that implies that it no longer requires it. if you check 1.0 and used it in the past you know that the package was only part of it, mono needs to be installed manually etc
     
  5. tatoforever

    tatoforever

    Joined:
    Apr 16, 2009
    Posts:
    4,364
    I'll check this out right now. :)
     
    Last edited: Sep 29, 2010
  6. adriaanza

    adriaanza

    Joined:
    Jun 24, 2010
    Posts:
    41
    good deal, thanks for the update.

    dreamora,

    http://eej.dk/angryant/behave/downloads/
     
  7. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    An additional active Mono runtime is indeed not required for running the 1.1 compiler - which by the way runs on Windows now as well :)
     
  8. sonicviz

    sonicviz

    Joined:
    May 19, 2009
    Posts:
    1,051
    A1. Been looking forward to this. New docs be up soon too?

    ty!
     
  9. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
  10. dart

    dart

    Joined:
    Jan 9, 2010
    Posts:
    211
    Really good news. Downloading this now
     
  11. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    great thing, exactly what I hoped to ehar :)

    thanks Emil
     
  12. fallingbrickwork

    fallingbrickwork

    Joined:
    Mar 16, 2009
    Posts:
    1,072
    Great Stuff. I have been meaning to look at this for quite a while. This new version is just the catalyst I needed.

    Regards,
    Matt.
     
  13. Jiong

    Jiong

    Joined:
    Dec 16, 2009
    Posts:
    22
    Great work!
    I have some problem.
    How can implement Priority Selector in behave?
    I need use Selector Node select 3 child node behavior by desirability (like Goal Evaluator), but selector node is sequence checking whether a child node selected in Behave.
    How can I do in behave?
     
  14. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Documentation update: Added a new video demonstrating how to get from an empty project to up and running with Behave plus brief introduction to the authoring environment:

    http://angryant.com/general/behave/video-behave-starting-from-scratch/

    @Jiong:
    I'm not entirely certain what it is you are after. Selectors and sequences are always evaluated left to right, so the branches you want considered first, should be placed leftmost of those which should be considered later. If you want further filtering, decorators and actions being evaluated to consider the validity of a branch should do the job.

    Unless I am misunderstanding what it is you are after?
     
  15. mikesgames

    mikesgames

    Joined:
    Apr 16, 2010
    Posts:
    1,071
    Thanks for this dude :)

    This rocks :)
     
  16. Jiong

    Jiong

    Joined:
    Dec 16, 2009
    Posts:
    22
    @AngryAnt
    i want select a goal by best desirability score;
    For example, i want select a goal in A,B,C;
    In behave case,
    we can do like this:
    Selector
    Sequence Sequence Sequence
    isA A isB B isC C
    but i want to select A, B, C by it desirability value;
    because of Selectors and sequences are always evaluated left to right, so i can only do like this:
    Check ACondition, Run A-> Checking BCondition, Run B->Check CCondition, Run C;
    so i can't do this logic:
    iterates through each goal option to best by desirability value->select this goal as next running;

    ======
    Other question, why change
    public BehaveResult Init[Name][Action/Decorator] (bool init, Tree sender);
    to
    public BehaveResult Init[Name][Action/Decorator] (Tree sender);
    public BehaveResult Tick[Name][Action/Decorator] (Tree sender);
    ?
    it look like not convenient, we have to coding more bind function and member variable;
     
  17. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    @Jiong:
    Ah like that. Yea I've been considering adding in a selector like that, but unfortunately I didn't have the time to include it in this release. I'll push it up the TODO list. Thanks for reminding me.

    Regarding the change in API, it was changed from

    BehaveResult Tick[Name][Action/Decorator] (bool init, Tree sender);

    to

    BehaveResult Init[Name][Action/Decorator] (Tree sender);
    BehaveResult Tick[Name][Action/Decorator] (Tree sender);

    In my experience most actions don't need to specifically handle the first tick and if they do, the setup ended up something like this anyway:
    Code (csharp):
    1. BehaveResult Tick[Name][Action/Decorator] (bool init, Tree sender)
    2. {
    3.     if (init)
    4.     {
    5.         DoSomething ();
    6.     }
    7.     else
    8.     {
    9.         DoSomethingElse ();
    10.     }
    11. }
    In which case I prefer the split up and not much is gained from keeping the old structure in stead of the new one.
     
  18. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    For anyone not familiar with behaviour trees, I added a direct link to an excellent introductory video by Alex J. Champandard of aiGameDev.com to the Behave documentation section.
     
  19. defjr

    defjr

    Joined:
    Apr 27, 2009
    Posts:
    436
    Pardon my ignorance, but is there any chance of this working on iOS?
     
  20. dart

    dart

    Joined:
    Jan 9, 2010
    Posts:
    211
  21. andy0305

    andy0305

    Joined:
    Aug 14, 2010
    Posts:
    4
    updates: The error is gone after i install the Mono framework. And thanks a lot for this great plug-in :)

    I need some help with it. Every time i try to build library debug i got this error message in console.

    Code (csharp):
    1. System.SystemException: Error running gmcs: Cannot find the specified file
    2.   at Mono.CSharp.CSharpCodeCompiler.CompileFromFileBatch (System.CodeDom.Compiler.CompilerParameters options, System.String[] fileNames) [0x00000] in <filename unknown>:0
    3.   at Mono.CSharp.CSharpCodeCompiler.CompileFromSourceBatch (System.CodeDom.Compiler.CompilerParameters options, System.String[] sources) [0x00000] in <filename unknown>:0
    4.   at Mono.CSharp.CSharpCodeCompiler.CompileAssemblyFromSourceBatch (System.CodeDom.Compiler.CompilerParameters options, System.String[] sources) [0x00000] in <filename unknown>:0
    5.   at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource (System.CodeDom.Compiler.CompilerParameters options, System.String[] fileNames) [0x00000] in <filename unknown>:0
    6.   at Behave.Editor.Compilers.Unity.Compile () [0x00000] in <filename unknown>:0
    7. UnityEngine.Debug:LogError(Object)
    8. Behave.Runtime.Resources:LogError(String)
    9. Behave.Editor.Compilers.Unity:Compile()
    10. Behave.Editor.Compiler:Run()
    11. Behave.Editor.Compiler:DoCompile(IBehaveAsset, Boolean)
    12. Behave.Editor.Compiler:Compile(IBehaveAsset, Boolean)
    13. BehaveMenu:Compile(Boolean) (at Assets/Behave/Editor/BehaveMenu.cs:55)
    14. BehaveMenu:Compile() (at Assets/Behave/Editor/BehaveMenu.cs:31)
    15. BehaveAssetEditor:Update() (at Assets/Behave/Editor/BehaveAssetEditor.cs:34)
    16. UnityEditor.EditorApplication:Internal_CallUpdateFunctions()
    The project is running with Unity3d 3.0 on Mac, and it's a clean project with only the behave package imported. I'm a newbie programmer. Really don't know what's going on with this error. Please help me out.
     
    Last edited: Oct 2, 2010
  22. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    That is really odd though. Is this the released version of Unity 3 or could it possibly be one of the pre-releases?
     
  23. ian-g

    ian-g

    Joined:
    May 10, 2010
    Posts:
    32
    I also have an error when building my behaviour library in release mode:

    It works fine in Debug mode though. And its pretty cool!

    I do however also get an error if I run it on my iPhone: “EXC_BAD_ACCESS”. I get this only if I use Script Call Optimization of "Fast but no exceptions". If I stick with "Safe and slow" it runs fine.

    Any ideas?
     
    Last edited: Oct 2, 2010
  24. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Not sure about the iPhone optimisation problem. I will look into that. Regarding the compile error, could you post a screenshot of the tree responsible for that compile error?
     
  25. ian-g

    ian-g

    Joined:
    May 10, 2010
    Posts:
    32
    Sure thing. Its just a simple setup to get my existing logic into a Behaviour Tree, then I can start doing what I want to improve the AI.

    The image is below. If you need anything tested for the Script Optimization issue, just shout.

    *deleted*
     
    Last edited: Oct 19, 2010
  26. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Just had a quick run through and it seems that release builds in general are broken. It is an easy fix and it will be out shortly. I intend to bundle it up with a few other changes though.
     
  27. andy0305

    andy0305

    Joined:
    Aug 14, 2010
    Posts:
    4
    It is the final release of Unity 3.0 pro with iphone advance. I have installed it over my old Unity 2.6.1 version. I haven't uninstall the older version first. So i'm not sure it's the reason cause the problem. And since the new version only override the pro version. My unity iphone 1.7 still there. It might be the reason why i have to manually install the Mono framework? by the way, I could see MonoDevelop 2.4 under my Unity 3.0 folder.
     
  28. sonicviz

    sonicviz

    Joined:
    May 19, 2009
    Posts:
    1,051
    I get the release compile error too.

    -> Can run on all Unity target platforms.

    I gather this also means Unity Pro + iPhone basic? or do you need iPhone advanced?

    I'm playing with the old behave 1 editor demo to get my head around how it works, but I think you should fix the old demo to work with Behave 1.1 and release that as well - would make it much easier to demonstrate how it works.

    ty!
     
    Last edited: Oct 8, 2010
  29. longshot

    longshot

    Joined:
    Sep 24, 2009
    Posts:
    71
     
  30. longshot

    longshot

    Joined:
    Sep 24, 2009
    Posts:
    71
    Have it fully working now, and it is great. Converted my AI system to using a behavior tree in less than two hours.

    Quick question though, let's say you use a decorator as a lock for a task, if you have two trees running, and don't want two tasks being run that affect the gameObjects position for example.

    I can see how you would lock, just by incrementing a variable in the decorator, and then having decorators check to see if the variable is above a certain threshold, and if it is, return failure.

    However, I don't see how you could unlock, without putting code into the task(s) that would decrement the count, which kills the point of having a decorator.

    Anyone know what the right way to do this would be?
     
  31. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Just finished uploading Behave 1.2. A few fixes in there including one for the broken release build. Also some additions: Priority selectors (thanks Jiong for pushing that up my TODO list again) and branch contexts.

    More information here: http://angryant.com/general/behave/behave-1-2-released/
     
  32. longshot

    longshot

    Joined:
    Sep 24, 2009
    Posts:
    71
    Quick question, is there a way to migrate trees over to the new version, or do they have to be redone from scratch?
     
  33. eviltenchi_84

    eviltenchi_84

    Joined:
    Feb 18, 2010
    Posts:
    99
    I am having a little trouble making scripts work with Behave, do you have any updated examples? The ones I looked at were from before 1.0 and were not really helpful.
     
  34. yinono

    yinono

    Joined:
    Sep 15, 2010
    Posts:
    27
    Hi
    If I add a new decorator to the tree and change its name and try to build the library | get an error message saying:
    "Comple error
    Internal compiler error."

    If I don't change the decorator name it does compile.

    Any Idea why?
     
    Last edited: Oct 14, 2010
  35. Toad

    Toad

    Joined:
    Aug 14, 2010
    Posts:
    298
    This looks great! Are you going to put together a demo for Behave 1.2?
     
  36. yinono

    yinono

    Joined:
    Sep 15, 2010
    Posts:
    27
    Hi,

    I just found out that the compile error I have only occur if I set a value for a floatParameter of a Decorator.
    I'll be glad for any help with that,Behave look's like a great tool.

    BTW: Is there any "official" place to post bug reports or discuss features of behave?
     
  37. yinono

    yinono

    Joined:
    Sep 15, 2010
    Posts:
    27
    longshot wrote:
    Just a guess:

    I think you can perform locking on the Init call of the decorator, and unlocking on the Reset call. It's look like the reset is called each time after the last Tick.

    Can any one confirm this?
     
    Last edited: Oct 17, 2010
  38. elias_t

    elias_t

    Joined:
    Sep 17, 2010
    Posts:
    1,367
    Hi. I am following the evolution of Behave and I have a question. Forgive me if it has been answered before but still, I haven't made my feet wet with behave:

    The goal would be to give to a character a basic behavior and as he evolves in the game to unlock and even create new behaviors for him. Also is there a possibility to save the characters current state of evolution and reuse in another level?

    Thank you.
     
  39. ggblake

    ggblake

    Joined:
    Oct 1, 2010
    Posts:
    11
    Trying desparately to get new Behave working in Unity3. Can anyone point out my error ( new to Behave coding). This is the Copper example

    import UnityEngine
    import BLCopperLibrary





    class EnemyPoliceGuy (MonoBehaviour):
    attackTurnTime = 0.7
    rotateSpeed = 120.0
    attackDistance = 17.0
    extraRunTime = 2.0
    damage = 1

    attackSpeed = 5.0
    attackRotateSpeed = 20.0

    idleTime = 1.6

    punchPosition = Vector3 (0.4, 0, 0.7)
    punchRadius = 1.1


    // sounds
    public idleSound as AudioClip // played during "idle" state.
    public attackSound as AudioClip // played during the seek and attack modes.

    attackAngle = 10.0
    lastPunchTime = 0.0

    // Will be used to store a reference to the enemy behavior tree
    enemyBehaviorTree as BLCopperLibrary.TreeType
    currentTarget as GameObject

    def Start():
    Debug.Log("On Start")
    characterController = GetComponent(CharacterController)

    animation.wrapMode = WrapMode.Loop

    animation.Play("idle")
    animation["threaten"].wrapMode = WrapMode.Once
    animation["turnjump"].wrapMode = WrapMode.Once
    animation["gothit"].wrapMode = WrapMode.Once
    animation["gothit"].layer = 1
    audio.clip = idleSound

    enemyBehaviorTree = BLCopperLibrary.InstantiateTree(BLCopperLibrary.TreeType.CopperBase_SimpleTree, Behave.Runtime.IAgent);
    Debug.Log("enemyBehaviorTree " + enemyBehaviorTree)

    def Update ():
    pass

    def FixedUpdate ():
    if enemyBehaviorTree.Tick(self, null) != Behave.Runtime.BehaveResult.Running:
    Debug.Log( "Resetting" );
    enemyBehaviorTree.Reset( self, null );

    def TickAction(action as int, sender as Tree, data as Object):
    castAction = cast(BLCopperLibrary.ActionType, action)
    Debug.Log("Action: " + castAction)
    if castAction == BLCopperLibrary.ActionType.WaitForTarget:
    LookForTarget()
    if currentTarget != null:
    return Behave.Runtime.BehaveResult.Success
    elif castAction == BLCopperLibrary.ActionType.Attack:
    Attack()
    return Behave.Runtime.BehaveResult.Success
    else:
    Debug.LogError( "Unknown action ID: " + action );

    return Behave.Runtime.BehaveResult.Failure;


    // We can normally get away with not decaring the types, but it's best to declare them to help Behave find the action
    def ResetAction(action as int, sender as Tree, data as Object ):
    pass

    def TickDecorator(decorator, sender, data ):
    return Behave.Runtime.BehaveResult.Success

    def ResetDecorator(decorator, sender, data ):
    pass


    def PlayIdleSound():
    // From the initial Idle method...
    // if idling sound isn't already set up, set it and start it playing.
    if idleSound:
    if audio.clip != idleSound:
    audio.Stop()
    audio.clip = idleSound
    audio.loop = true
    audio.Play() // play the idle sound.

    // Don't do anything when idle
    // The perfect time for the player to attack us
    yield WaitForSeconds(idleTime)

    // Attempts to lock on a target
    def LookForTarget():
    PlayIdleSound()
    currentTarget = null
    // Verify if there's anyone tagged "Target" nearby so we can attack it
    // This will be done using simple proximity calculation for now
    targets = GameObject.FindGameObjectsWithTag("Enemy")
    for target in targets:
    offset = transform.position - target.transform.position

    // if player is in range again, stop lazyness
    // Good Hunting!
    if offset.magnitude < attackDistance:
    Debug.Log("Will attack " + target.transform.GetInstanceID())
    currentTarget = target
    break
    if currentTarget == null:
    animation.Stop("attackrun")
    animation.Play("idle")

    def Attack():
    animation.Stop("idle")
    animation.Play("attackrun")
     
  40. yinono

    yinono

    Joined:
    Sep 15, 2010
    Posts:
    27
    I use c#, but I think the API is the same in java script.

    If you use behave 1.2 the signature of TickAction is different from what you used

    you used def TickAction(action as int, sender as Tree, data as Object)
    but the function signature in C# is

    Tick(Behave.Runtime.Tree sender, bool init)

    and to get the action id you use sender.ActiveID
     
  41. gl33mer

    gl33mer

    Joined:
    May 24, 2010
    Posts:
    281
    That reminds me :) - I've asked this before and I know the documentation for Behave is still being written:

    How would I go about using Javascript and Behave? Any working examples/projects?

    Thanks.
     
  42. ggblake

    ggblake

    Joined:
    Oct 1, 2010
    Posts:
    11
    Thanks,

    One major glitch seems to be:
    enemyBehaviorTree = BLCopperLibrary.InstantiateTree(BLCopperLibrary.Tr eeType.CopperBase_SimpleTree, Behave.Runtime.IAgent);
     
  43. ggblake

    ggblake

    Joined:
    Oct 1, 2010
    Posts:
    11
    Thanks,

    One major glitch seems to be:
    enemyBehaviorTree = BLCopperLibrary.InstantiateTree(BLCopperLibrary.Tr eeType.CopperBase_SimpleTree, Behave.Runtime.IAgent);
     
  44. sonicviz

    sonicviz

    Joined:
    May 19, 2009
    Posts:
    1,051
    I'd really like to use this but don't have the time to waste trying to scratch my head over how ytou actually get it working.
    I had a play with the editor and have been reading up on behavior trees in the meantime.
    The video links were helpful, but I'll work on some other things till the sample project for 1.2 gets released.
     
  45. ian-g

    ian-g

    Joined:
    May 10, 2010
    Posts:
    32
    Whatever fixes you did for Behave 1.2 has also corrected the iPhone Call Script Optimisations error that I was seeing the other week. I can now successfully run it on the device using "Fast but no exceptions".

    Brilliant!
     
  46. ian-g

    ian-g

    Joined:
    May 10, 2010
    Posts:
    32
    @ggblake:

    I don't use Boo, but I've attached my Copper example (EnemyGuy script, in c#). Its good to go with Behave 1.2.

    Ian
     

    Attached Files:

  47. longshot

    longshot

    Joined:
    Sep 24, 2009
    Posts:
    71
    In a nutshell -

    Have a class derive from the IAgent interface-

    Code (csharp):
    1.  
    2. public class SomeClass : MonoBehaviour, IAgent
    3.  
    Have an instance variable for the tree-

    Code (csharp):
    1.  
    2. private Behave.Runtime.Tree tree;
    3.  
    In the classes Awake() method, initialize the tree variable, you will need to reference the compiled library made by the tree editor.
    Code (csharp):
    1.  
    2. tree = BLNewBehaveLibrary0.InstantiateTree( BLNewBehaveLibrary0.TreeType.SUPERAWESOME_potato, this );
    3.  
    Implement tick and reset in the class-
    Code (csharp):
    1.  
    2.     public static BehaveResult UnhandledID( int id )
    3.     {
    4.         if( BLNewBehaveLibrary0.IsAction( id ) )
    5.         {
    6.             Debug.LogError( "Unhandled Action: " + ( ( BLNewBehaveLibrary0.ActionType )id).ToString() );   
    7.         }
    8.         else if( BLNewBehaveLibrary0.IsDecorator(id) )
    9.         {
    10.             Debug.LogError( "Unhandled decorator: " + (( BLNewBehaveLibrary0.DecoratorType)id).ToString() );
    11.         }
    12.         else
    13.         {
    14.             Debug.LogError("Invalid ID: " + id );  
    15.         }
    16.         return BehaveResult.Success;
    17.     }
    18.    
    19.    
    20.    
    21.     public BehaveResult Tick( bool init, Behave.Runtime.Tree sender )
    22.     {
    23.         return UnhandledID( sender.ActiveID ); 
    24.     }
    25.    
    26.     public void Reset( Behave.Runtime.Tree sender )
    27.     {
    28.        
    29.     }
    30.  
    In 1.2 the method signature for Tick is a little different -
    Code (csharp):
    1.  
    2.     public BehaveResult Tick( Behave.Runtime.Tree sender, bool init )
    3.     {
    4.         return UnhandledID( sender.ActiveID ); 
    5.     }
    6.  
    In 1.2, you also need to implement the SelectTopPriority method, I haven't played with it yet, so I just give it an empty implementation for now -

    Code (csharp):
    1.  
    2.     public int SelectTopPriority( Behave.Runtime.Tree sender, params int[] IDs )
    3.     {
    4.         return 0;  
    5.     }
    6.  
    You will need to tick the tree. Whenever you tick the tree, it will do a depth-first traversal( in laymans terms, it will start at the root, then go downwards through the tree, going left ).

    How often you tick the tree depends on the type of game you are making, and the scope of AI. For a character in an action game, you would most likely want to tick in either Update or FixedUpdate.

    If you were doing a turn based strategy game, it would make more sense to tick every turn than every frame.

    Code (csharp):
    1.  
    2. tree.Tick(this,null);
    3.  
    This is all of the logic you need to do to get the tree running. However, you will want to link the tree to some actions/decorators/whatever. For Actions, to have the tree call the correct method, you need to give it the correct name. The convention for actions is - "Tick" + "NameOfTheActionInTheTreeEditor" + "Action". So if you have an action named "AmIAtFullHealth" in the tree editor, you would name the method "TickAmIAtFullHealthAction" in the source.

    Code (csharp):
    1.  
    2.     public BehaveResult TickAmIAtFullHealthAction( Behave.Runtime.Tree sender )
    3.     {
    4.         if( hitPoints < maxHitPoints)
    5.             return BehaveResult.Failure;
    6.         else
    7.             return BehaveResult.Success;
    8.     }
    9.  
    Now you should be ready to rock. When it reaches an AmIAtFullHealthAction in the tree, it will call the method, and proceed depending on the result. There is also BehaveResult.Running for actions that aren't going to immediately return success or failure.

    Hope that helps.
     
    Last edited: Oct 20, 2010
  48. sonicviz

    sonicviz

    Joined:
    May 19, 2009
    Posts:
    1,051
    Hey tyfm for that Longshot. Very helpful! AngryAnt should get you to help on the documentation! (yes, there are some of us ijits out there that actually rtfm and play with examples to learn;-)
     
  49. ggblake

    ggblake

    Joined:
    Oct 1, 2010
    Posts:
    11
    Fantastic.... it works.. Thanks for the help
     
  50. longshot

    longshot

    Joined:
    Sep 24, 2009
    Posts:
    71
    A Bug -
    Parallels don't seem to be working entirely correctly, or there is something I don't understand. If I have a parallel, with it's Component Completion set to One, and its child completion set to Success, I would expect it to complete when the first child returns Success. However, it will keep ticking past children that have returned success.

    A Question - How do you have a decorator modify the return value of its child?