Reputation: 1
I'm making a game in Java and I want to create a character that moves randomly. The one I made is very spastic. I basically want to add a delay between random numbers generated. I'm a beginner so don't judge my code lol
public class Monster extends Entity{
private World world;
Image monster;
public Monster(int x, int y, World world) {
super(x, y, world);
w = 32;
h = 32;
this.world = world;
}
public void render(GameContainer gc, Graphics g) throws SlickException{
super.render(gc, g);
monster = new Image("gfx/world/monster.png");
g.drawImage(monster, x, y);
}
public void update(GameContainer gc, int delta) throws SlickException{
super.update(gc, delta);
Random move = new Random();
int number;
for(int counter=1; counter<=1;counter++){
number = move.nextInt(4);
System.out.println(number);
if(number == 0){
setDy(-1);
}else if(number == 1){
setDx(-1);
}else if(number == 2){
setDy(5);
}else if(number == 3){
setDx(5);
}else{
setDx(0);
setDy(0);
}
}
}
}
Upvotes: 0
Views: 825
Reputation: 319
This is a common technique used on games to have a different update and render rate. What you have to do is (examples in pseudo code):
1 - Initialize a time variable - DateTime lastUpdate = new DateTime();
Every time you enter in the loop:
2 - Check if a certain time has passed - lastUpdate.hasPassed(X_TIME, new DateTime());
3 - if the time has passed (last line was true) lastUpdate = new DateTime();
4 - Else return
Upvotes: 1
Reputation: 11579
Try to add
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
e.printStackTrace();
}
where ms
- how many miliseconds, e.g. 1000
Upvotes: 0
Reputation: 3573
You'll want to encapsulate the NPC movement in a separate thread, and within that thread call thread.sleep to pause the movement.
Here is a good tutorial on how to define threads, and the oracle docs show an example of a thread that sleeps.
Upvotes: 0