PDA

View Full Version : ideal npc walking code



nico
May 6th, 2006, 12:23 AM
ahm, just wanna ask on how can i make my npc walk around the stage. the animations of walking are all done, i only need a code on how can i implement it. thanks guys.

Dauntless
May 6th, 2006, 04:25 AM
With that little information, no one can give you a good answer.

IF your game is tilebased, you could use my A* implementation:
www.dauntless.be

nico
May 6th, 2006, 04:59 AM
oooppss sory, my game is art based not tile based.

Dauntless
May 6th, 2006, 06:38 PM
Well then it's even harder to give a good answer... You should store some keypoints and make a network. Like: you can get to point A from point B through 'D-E-C-F'. If your map is small, you can hardcode all the routes. If your map is bigger, you will have to make up an algorithm that find the shortest route from point A to B. It's not really that hard... Just store all the connections of a node inside the node and then start looping.

nico
May 6th, 2006, 08:05 PM
the question is HOW???

InfestedDemon
May 6th, 2006, 08:11 PM
exactly. you need to think hard, tile-based would be easier :P

Nich
May 7th, 2006, 01:32 AM
wait, do you want just random npc walking? Or do you want them to go in a specific path?

nico
May 7th, 2006, 07:50 AM
yup, the npc walks only at random.

Nich
May 7th, 2006, 11:43 AM
Ok. Sec, I'll write up a quick random walking code

Edit:
ActionScript Code:

this.onEnterFrame = function(){

dirpicked = false
dir = "right"
dirnum = 0
movedist = 100
speed = 5
totalmove = 0
if(!dirpicked)
{
dirnum = Math.random()*4
if(dirnum < 1)
{
dir = "right"
}
if(dirnum < 2)
{
dir = "left"
}
if(dirnum < 3)
{
dir = "up"
}
if(dirnum <= 4)
{
dir = "down"
}
dirpicked = true
}
if(dirpicked)
{
if(dir == "right")
{
npc._x += speed
totalmove += speed
}
if(dir == "left")
{
npc._x -= speed
totalmove += speed
}
if(dir == "up")
{
npc._y -= speed
totalmove += speed
}
if(dir == "down")
{
npc._y += speed
totalmove += speed
}
if(totalmove >= movedist)
{
totalmove = 0
// at this point you could set a timer so that the character doesn't constantly walk
dirpicked = false
}
}
}




It might need to be adapted, but it's a start

nico
May 8th, 2006, 08:26 AM
i get it. but another question. what if the npc walked through a wall??? how can the npc know that a wall is near so that it will change direction??? thanks for the code!!!:beam:

Joppe
May 8th, 2006, 11:21 AM
like..
if(_root.wall.hitTest(this._x,this._y,true)){
dirpicked = false;
}
maybe..

nathan99
May 8th, 2006, 06:23 PM
Yell ya what, I will right you a better code.. give me a day or so because I have school now;)

nico
May 9th, 2006, 09:03 AM
im looking forward to that nathan. thanks:)