# Smooth Npc Movement

I have an Npc in my rpg that moves around based on a Random() variable. My main goal is to have him walk in a random direction a small bit every 2 seconds. I only want him to move about 32 pixels every time he walks.

public void npcLogic()
{
rand = new Random();

now = System.nanoTime();

if((now - lastMove) >= moveSpeed)
{
if(rand.nextFloat() >= .4)
{
Game.npcX += 32;
lastLook = 3;
}
else if(rand.nextFloat() >= .3)
{
Game.npcX -= 32;
lastLook = 2;
}
else if(rand.nextFloat() >= .2)
{
Game.npcY += 32;
lastLook = 1;
}
else if(rand.nextFloat() >= .1)
{
Game.npcY -= 32;
lastLook = 0;
}
lastMove = now;
}
}


The problem is he jumps to his destination rather than smoothly walking there. I have tried setting a timer to move him slightly for a specific amount of time like

Long smNow = 0L;
Long smLast = 0L;
Long smSpd = 5000000L;

public void npcLogic()
{
rand = new Random();

now = System.nanoTime();

if((now - lastMove) >= moveSpeed)
{
if(rand.nextFloat() >= .4)
{
smNow = System.nanoTime();
while((smNow - smLast) >= smSpd)
{
Game.npcX += Player.SPEED;
lastLook = 3;
}
smLast += smNow;
}
lastMove = now;
}
}


but this Stops movement of the player character and he still jumps, and now way too far. So does anyone have any suggestion to make the Npc move smoothly while the player character can still move around?

• This is a top down game? Grid based or free movement? Commented Dec 15, 2014 at 5:56
• Top-down, free movement Commented Dec 15, 2014 at 21:35

## 1 Answer

You need to set to NPC a new target once in a while (e.g. each 5sec) and move it towards the target each tick little by little. Then it will be smooth.

To avoid sharp turns upon setting a new target, you can mix target positions between old and new target for a second or two.

Additionally, you might want to Google for "Steering behavior"

• Well what I'm doing for the Npc movement is having him move just a little in a random direction. I don't want him to continually move. Commented Dec 15, 2014 at 21:39
• @Twiggy, that's your problem... You need the NPC to be continually moving or else the NPC will appear to "jump" between frames. Commented Dec 15, 2014 at 23:17
• @Twiggy: You need to explain your goals better. Edit the question! :) Commented Dec 16, 2014 at 5:06