[PloobsEngine] Tutorial 10 – Finite State Machine


This tutorial will show how to use  the ploobsengine build in finite state machine. (the complet list of tutorials can be found here) The code for this sample is NOT included in the advanced demos package avaliable for download (but you can easily copy and past from this post).

Finite State Machine (FSM) is a very classic (and simple) AI technique used in almost all kinds of games, for a good explanation visit this site.

In this tutorial, we are assuming that you know what FSM is.

In Ploobs, the only thing you need to do is to extend the IState class. It has some simple methods that will be automatically called by the FSM control object. The important ones are the UpdateState() used to update the state and the NextState() used to make the states transitions .

The following piece of code shows a generic state (made specially for this sample). It will only delegate its responsabilities to other methods using lambda expression:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PloobsEngine.IA;
using PloobsEngine.SceneControl;
using Microsoft.Xna.Framework;

namespace EngineTestes.AI.FSM
{
    class StateSample : IState
    {
        public StateSample(String Name,IObject Object)
        {
            this.Object = Object;
            this.name = Name;
        }

        IObject Object;
        #region IState Members

        public Func NextStateFunc;
        public Action InitFunc;
        public Action FinishFunc;
        public Action UpdateFunc;

        public void Init()
        {
            if (InitFunc != null)
                InitFunc(Object);
        }

        public string NextState()
        {
            if (NextStateFunc != null)
                return NextStateFunc(Object);
            return null;
        }

        public void UpdateState(Microsoft.Xna.Framework.GameTime gameTime)
        {
            if (UpdateFunc != null)
                UpdateFunc(gameTime, Object);
        }

        public void Finish()
        {
            if (FinishFunc != null)
                FinishFunc(Object);
        }

        #endregion

        #region IState Members

        String name;
        public string Name
        {
            get { return name; }
        }

        #endregion
    }
}

We are just overriding some functions functions that are self explanatory.

The special one is the NextState, it is called all frames after the UpdateState and is responsible for return the next state of the FSM, if it returns something different from null, the FSM will change its state according with the state name returned and will call the Finish methof of the current state and the Init of the next state.

The following code shows the PloobsScene that will use the FSM. Look at the state definitions and the FSM initialization code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PloobsEngine.SceneControl;
using PloobsEngine.Physics;
using PloobsEngine.Modelo;
using PloobsEngine.Material;
using PloobsEngine.Engine;
using PloobsEngine.Physics.Bepu;
using Microsoft.Xna.Framework;
using PloobsEngine.Cameras;
using EngineTestes.AI.FSM;
using PloobsEngine.IA;
using Microsoft.Xna.Framework.Input;

namespace ProjectTemplate
{
    public class FSMScreen : IScene
    {
        StateMachine fsm;
        ///
        /// Sets the world and render technich. ///
        ///The render tech.
        ///The world.
        protected override void SetWorldAndRenderTechnich(out IRenderTechnic renderTech, out IWorld world)
        {
            ///create the IWorld
            world = new IWorld(new BepuPhysicWorld(-0.97f, true, 1), new SimpleCuller());

            ///Create the deferred technich
            ForwardRenderTecnichDescription desc = new ForwardRenderTecnichDescription();
            renderTech = new ForwardRenderTecnich(desc);
        }

        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            base.LoadContent(GraphicInfo, factory, contentManager);

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.White), TextureType.DIFFUSE);
                ///Physic info (position, rotation and scale are set here)
                BoxObject tmesh = new BoxObject(Vector3.Zero, 1, 1, 1, 10, new Vector3(1000, 1, 1000), Matrix.Identity, MaterialDescription.DefaultBepuMaterial());
                tmesh.isMotionLess = true;
                ///Forward Shader (look at this shader construction for more info)
                ForwardXNABasicShader shader = new ForwardXNABasicShader();
                ///Deferred material
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                ///The object itself
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                ///Add to the world
                this.World.AddObject(obj);

                ///create the FSM
                fsm = new StateMachine();
                ///atach the fsm to the object using the attachment property (there are lots of ways of doing this, like extending the iobject class)
                AttachmentUpdate atachment = new AttachmentUpdate(
                    (a, b) => fsm.UpdateFSM(b)
                        );
                obj.IObjectAttachment.Add(atachment);

                ////Simple State example
                ///Press Space to go to state2 and press enter in state 2 to get back to state1 =P
                {
                    StateSample state1 = new StateSample("state1",obj);
                    state1.NextStateFunc =
                      (a) =>
                      {
                          KeyboardState kstate = Keyboard.GetState();
                          if (kstate.IsKeyDown(Keys.Space))
                          {
                              return "state2";
                          }
                          return null;
                      };
                    fsm.AddState(state1);

                    ///SET THE CURRENT STATE
                    fsm.SetCurrentState(state1.Name);
                }

                ///create state 2 (similar)
                {
                    StateSample state2 = new StateSample("state2",obj);
                    state2.NextStateFunc =
                      (a) =>
                      {
                          KeyboardState kstate = Keyboard.GetState();
                          if (kstate.IsKeyDown(Keys.Enter))
                          {
                              return "state1";
                          }
                          return null;
                      };
                    fsm.AddState(state2);
                }
            }

            ///add a camera
            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo.Viewport));
        }

        /// This is called when the screen should draw itself. ///
        protected override void Draw(GameTime gameTime, RenderHelper render)
        {
            base.Draw(gameTime, render);

            ///Draw some text on the screen
            render.RenderTextComplete("Demo: FSM sample", new Vector2(GraphicInfo.Viewport.Width - 315, 15), Color.White, Matrix.Identity);
            ////current state info
            render.RenderTextComplete("Current State: " + fsm.GetCurrentState().Name, new Vector2(GraphicInfo.Viewport.Width - 315, 35), Color.White, Matrix.Identity);
        }

    }
}

We just create the FSM object, attached it to an IObject using a AttachmentUpdate (so the update method of the FSM will be called, see the previous tutorials), then create some states (the behavior of them were defined using the lambda expressions).

We always need to tell the FSM the first state. (setCurrentState call)

You can use the FSM anywhere you want (in menus, in objects …) you just need to call its update all the frames.

The class AttachmentUpdate extends the IObjectAttachment. It has its update method called all the frames. It is a ploobs facility to help us binding a custom behavior to an IObject without needing to extend it.

This is all for today, the next tutorial will talk about the PloobsEngine PathFinding utilities.

, , ,

  1. #1 by http://news.christianlouboutinreplica.pw/christianlouboutinreplicapw/594.asp on 28 de maio de 2017 - 5:09 am

    I have it headphonesfor the mother towards moms evening, plus she completely enjoyed things! Their quite pretty headphonesand saying on the card which comes inside container is very emotional!! And premium of the beads was great!

  2. #2 by http://www.aim.org.in/system/67.html on 28 de maio de 2017 - 5:10 am

    I had gotten it headphonestowards my personal mother for the mothers time, as well as she completely loved they! Its truly pretty headphonesand the suggesting on the card which is comes in container is really sentimental!! As well as the premium of the beads was great!

  3. #3 by http://www.herreavdelingen.no/userfiles/file/486.html on 28 de maio de 2017 - 5:12 am

    Awesome headphonesget, nicely listed and exactly what is actually presented. Gorgeous gift box and/or poem also enclosed. Awesome towards mother’s day!

  4. #4 by bvlgar rings replica on 28 de maio de 2017 - 6:48 am

    it comes down within a perfect container appears great but it is slightly mini even for our mothers wrist however it seems ideal really really want things had been longer

  5. #5 by http://www.sundbirsta.com/ukclreplica.asp on 28 de maio de 2017 - 6:48 am

    I have this gifts for the my personal mom for Christmas time mainly because she is a jewelry freak. Some sort of one thing she cannot use a great deal to is, bracelets. I bought this girl your appeal bracelet to whenever she started they yesterday she absolutley loved that it! This time the issue is, her getting information technology in furthermore down by just by herself. Haha… in general great system, they sent and/or arrived extremely very early and/or our mother was enjoying things. Thank people.

  6. #6 by http://news.portside.xyz/portsidexyz/502.asp on 28 de maio de 2017 - 7:04 am

    But not just as fancy as part of real world provided moms wrist is never 2small do not buy information technology influence information technology be tight .. it is attractive however anything yur 5year existing makes . No some sort of lower it really is a ok present on offer but not per wow gifts…cant get wrong in case dont has far to blow for a gift subsequently attain information technology

  7. #7 by http://www.pacesetterfund.org/session/66.html on 28 de maio de 2017 - 7:05 am

    Bought our as being a present towards my personal mama furthermore she enjoyed information technology. terrific excellent sweet price tag additionally the mother enjoyed they. Furthermore delivered extremely accelerated. So if you need a present quick and you such as this compared to this is actually the 1 one should get!

  8. #8 by buy cheap shoes online on 28 de maio de 2017 - 7:31 am

    Anytime you see a “full” tag on a shirt you ought to presume that it is quite larger than that of normal one.|Your Facebook enthusiast web page may be the initial time a consumer arrives into contact with you. You will have to be extremely careful for few things. Yellow color is effortlessly visible via the mist and fog occasions.|The big guys where still at reverse ends of the buying mall. Incentives might also differ from the kinds of survey you take. From Fashion pearl sets to Trendy pearl set.|Are you looking for a comfy nightgown or sexy women’s intimate lingerie?

  9. #9 by schauen sie sich hier on 28 de maio de 2017 - 8:43 am

    Entscheidend ist an welcher Funkzelle das Handy zum aktuellen Zeitpunkt angemeldet ist.

  10. #10 by http://www.cozy-time.co.uk/londonprice.asp on 28 de maio de 2017 - 9:33 am

    I have your gifts towards the mother towards Christmas time considering she was any precious jewelry freak. The particular one thing she cannot put on much concerning was, bracelets. I bought the lady your allure bracelet and/or once she launched this yesterday she absolutley liked they! Now the problem is, her acquiring this in to off of through by herself. Haha… in general awesome product, that it delivered to arrived completely early furthermore my personal mother are experiencing it. Thank you.

  11. #11 by souped up camaro on 28 de maio de 2017 - 10:24 am

    How could any of this be better stated? It couldn’t.

  12. #12 by replica christian louboutin sale on 28 de maio de 2017 - 10:58 am

    it comes down in a awesome package appearance awesome but its a bit tiny consistent for the my moms wrist however it looks very good really really want they is much longer

  13. #13 by http://www.bmx-saintquentin.com/flats.asp on 28 de maio de 2017 - 10:59 am

    it comes within a pretty container seems ideal and yet the somewhat mini including concerning my personal moms wrist however it styles great just want information technology is extended

1 440 441 442
(não será publicado)