Create a thread in xna Update method to find path?

Posted by Dan on Game Development See other posts from Game Development or by Dan
Published on 2012-10-29T23:57:58Z Indexed on 2012/10/30 5:23 UTC
Read the original article Hit count: 276

Filed under:
|
|
|
|

I am trying to create a separate thread for my enemy's A* pathfinder which will give me a list of points to get to the player. I have placed the thread in the update method of my enemy. However this seems to cause jittering in the game every-time the thread is called. I have tried calling just the method and this works fine. Is there any way I can sort this out so that I can have the pathfinder on its own thread? Do I need to remove the thread start from the update and start it in the constructor? Is there any way this can work. Here is the code at the moment:

 bool running = false;
 bool threadstarted;
 System.Threading.Thread thread;


public void update()
{
                if (running == false && threadstarted == false)
                {
                    thread = new System.Threading.Thread(PathThread);

                    //thread.Priority = System.Threading.ThreadPriority.Lowest;
                    thread.IsBackground = true;
                    thread.Start(startandendobj);
                    //PathThread(startandendobj);
                    threadstarted = true;
                }
}

        public void PathThread(object Startandend)
        {

            object[] Startandendarray = (object[])Startandend;
            Point startpoint = (Point)Startandendarray[0];
            Point endpoint = (Point)Startandendarray[1];

            bool runnable = true;
            // Path find from 255, 255 to 0,0 on the map
            foreach(Tile tile in Map)
            {
                if(tile.Color == Color.Red)
                {
                    if (tile.Position.Contains(endpoint))
                    {
                        runnable = false;
                    }
                }
            }
            if(runnable == true)
            {
                running = true;
                Pathfinder p = new Pathfinder(Map);
                pathway = p.FindPath(startpoint, endpoint);     
                running = false;
                threadstarted = false;

            }


        }

© Game Development or respective owner

Related posts about XNA

Related posts about c#