Thread: Follow player
View Single Post
  #1  
Old 05-11-2001, 06:56 AM
Admins Admins is offline
Graal Administration
Join Date: Jan 2000
Location: Admins
Posts: 11,693
Admins has much to be proud ofAdmins has much to be proud ofAdmins has much to be proud ofAdmins has much to be proud ofAdmins has much to be proud ofAdmins has much to be proud of
Here an example for a class 'followers'.
First an NPC that joins that class:

NPC Code:

if (created) {
showcharacter;
}
if (playerchats) {
if (strequals(#c,follow)) {
setstring this.owner,#a;
followPlayer();
}
if (strequals(#c,stop)) {
setstring this.owner,;
stopingFollow();
}
}
function stopingFollow() {
setcharani idle,;
message STOP;
sleep 3;
message;
}
join followers;



And here the class file:

NPC Code:

function followPlayer() {
cannotwarp;
setarray this.followpos,0;
while (true) {
noowner = true;
with (getplayer(#s(this.owner))) {
noowner = false;
if (!strequals(#F,#L)) {
// Player leaved the level, so follow him
setarray this.followpos,0;
dir = playerdir;
warpto #F,playerx,playery;
} else {
//
// Follow the player
//
px = playerx;
py = playery;

// Add one step to the list if the player has moved
alen = arraylen(this.followpos);
if (alen<2 || this.followpos[alen-2]!=px || this.followpos[alen-1]!=py) {
setarray this.followpos,alen+2;
this.followpos[alen] = px;
this.followpos[alen+1] = py;
}
// Only save 4 steps, so delete one entry at the beginning
// if there are too many
if (arraylen(this.followpos)>4*2) {
for (i=0; i<4; i++) {
this.followpos[i*2] = this.followpos[(i+1)*2];
this.followpos[i*2+1] = this.followpos[(i+1)*2+1];
}
setarray this.followpos,4*2;
}

// Get the new position (oldest saved step)
nx = this.followpos[0];
ny = this.followpos[1];

// Setting direction
if (abs(nx-x)>abs(ny-y)) {
if (nx<x) dir = 1; else dir = 3;
} else if (abs(nx-x)<abs(ny-y)) {
if (ny<y) dir = 0; else dir = 2;
}
if (nx==px && ny==py) dir = playerdir;

// Setting animation
if (onwater(nx+1.5,ny+2))
this.animode = 2;
else if (x==nx && y==ny)
this.animode = 0;
else
this.animode = 1;
setAnimation();

// Applying the new position
x = nx;
y = ny;
}
}
if (noowner==true)
break;
sleep 0.1;
}
stopingFollow();
}
function stopingFollow() {
this.animode = 0;
setAnimation();
}
function setAnimation() {
if (startswith(bomy,#3(-1))) {
if (this.animode==0)
setcharani bomy_idle,;
else if (this.animode==1)
setcharani bomy_walk,;
else if (this.animode==2)
setcharani bomy_kick,;
} else {
if (this.animode==0)
setcharani idle,;
else if (this.animode==1)
setcharani walk,;
else if (this.animode==2)
setcharani swim,;
}
}



The follow script uses the array this.followpos
to remember the walking position of the
player. You can see that the NPC is overwriting
the function stopingFollow() to implement
its own code (saying 'STOP' for 3 seconds).
You can see that using the followers script
is very simple, you only need to set this.owner,
then call followPlayer()

If you have questions or improvements then
let me know