Best idea is to use a timer/OnPlayerUpdate to calculate difference between the player's last position and new position, and adding the result to a variable.
The formula for calculating the distance between two sets (two sets because we only want to calculate x and y planes, I assume) of cartesian coordinates is:
Код:
sqrt( ((x2-x1)^2) + ((y2-y1)^2) )
... Which could be wrote as:
a = (x2-x1)
b = (y2-y1)
sqrt( (a*a) + (b*b) )
... Which is essentially Pythagoras' Theorem, which finds the length of the hypotenuse of a right angled triangle.
Because we know two sides (x and y), we can use these to calculate the length (or distance between) the two points.
This, implemented into PAWN would be something like:
pawn Код:
stock Float:dif_between_coords_xy( Float:x1, Float:y1, Float:x2, Float:y2 )
{
//Formula to calculate difference between two sets of cartesian coords:
//sqrt( ((x2-x1)^2) + ((y2-y1)^2) )
new Float:a = (x2 - x1),
Float:b = (y2 - y1),
Float:distance;
//Assign distance the result of the formula.
distance = floatsqroot( floatpower(a,2) + floatpower(b,2) );
//Return distance.
return distance;
}
Now we have the function, we can create the variables used to hold the player's last position and global distance travelled:
pawn Код:
//Last position X:
new Float:LastPosX [ MAX_PLAYERS ];
//Last position Y:
new Float:LastPosY [ MAX_PLAYERS ];
//Total distance travelled:
new Float:tDistance[ MAX_PLAYERS ];
We can now update these variables upon a timer or OnPlayerUpdate (I'll use OnPlayerUpdate in this example, to avoid confusion):
pawn Код:
public OnPlayerUpdate(playerid)
{
//Variables for the player's current position:
new Float:fX, Float:fY, Float:fZ;
if( IsPlayerInAnyVehicle( playerid ))
{
//If the player is in any vehicle, get the vehicles position:
GetVehiclePos( GetPlayerVehicleID(playerid), fX, fY, fZ );
}
else
{
//If the player isn't in any vehicle, get the players position instead:
GetPlayerPos( playerid, fX, fY, fZ );
}
if( LastPosX[ playerid ] != 0 && LastPosY[ playerid ] != 0 )
{
//If the player's last position X&Y are not 0:
//(They've been initialised):
//Add the difference between the two sets of coordinates to the distance travelled.
tDistance[ playerid ] += dif_between_coords_xy( fX, fY, LastPosX[ playerid ], LastPosY[ playerid ] );
}
//Set the last position variables to the player's current position, for the next update.
LastPosX[ playerid ] = fX;
LastPosY[ playerid ] = fY;
return 1;
}