• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with thread.sleep(), Or need a different solution  RSS feed

 
Noah Jones
Greenhorn
Posts: 3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, let me give you a quick rundown of my situation.

I am making a simple, top-down RPG/dungeon exploration game (think Legend of Zelda), and I have my main class, which does all the drawing, updating, etc. I have the player all figured out, and am working on NPC's. The problem I am running into is that when I call my AI runner method I need the NPC to move in a random direction for a random time between 0 and 3 seconds. However, I cannot just set the NPC's velocity and call thread.sleep() because that pauses the whole thread for the entire game, thus making the players movement choppy and wacky.

I have tried making a new Thread in the main class and another one in the NPC class as instance variables, but when I call one of them the other seems to pause too.

Here is a loose skeleton of the code:

//Total AI for the npc

[Added code tags - see UseCodeTags for details]

So, am I just missing something obvious? Also, if you have a way to let the NPC move with Thread.sleep()I would love to hear it. Please help!

Thanks in advance
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Noah. Welcome to the Ranch!

I'm not sure there's enough information to suggest a complete solution there. But possibly one reason that NPCThread.sleep(1000) isn't doing what you expect is that sleep() is a static method of the Thread class. If you look at the documentation, it says:
Causes the currently executing thread to sleep...


So you can never make another thread wait for a certain amount of time like that. It should really always be called as Thread.sleep(1000) - calling sleep on a specific Thread reference is valid but misleading.
 
Noah Jones
Greenhorn
Posts: 3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew.

I solved it by just using two variables, distTraveled and startDistance, and a simple while loop to check whether the distance traveled is less than, say 32 pixels.

Just in case anyone else happens upon my post.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!