Automatic Gates

From SA-MP Wiki

Revision as of 18:30, 23 October 2009; view current revision
←Older revision | Newer revision→
Jump to: navigation, search

Getting ready

Before you begin scripting your moving gates, we'll need to have a few functions ready - we will use the function PlayerToPoint(). PlayerToPoint is a function that checks player's distance from a certain point and then according to what the check says, returns true (the player is near the point, within the radius) or false (player is out of the given radius).

Important note: Since 0.3, you have IsPlayerInRangeOfPoint to your availability. This is a native function and works faster than PlayerToPoint.
PlayerToPoint(Float:radius, playerid, Float:X, Float:Y, Float:Z)
{
    new Float:oldpos[3], Float:temppos[3];
    GetPlayerPos(playerid, oldpos[0], oldpos[1], oldpos[2]);
    temppos[0] = (oldpos[0] -X);
    temppos[1] = (oldpos[1] -Y);
    temppos[2] = (oldpos[2] -Z);
    if(((temppos[0] < radius) && (temppos[0] > -radius)) && ((temppos[1] < radius) && (temppos[1] > -radius)) && ((temppos[2] < radius) && (temppos[2] > -radius)))
    {
        return true;
    }
    return false;
}

Additionally, you need to have coordinates of 2 locations - closed and open gate (X, Y, Z) and the closed gate must be created.

// this will go above main(), as this is a global variable
new c_gate;
// this will go under OnGameModeInit or OnFilterScriptInit
c_gate = CreateObject(object_ID, closed_X, closed_Y, closed_Z, closed_rad_X, closed_rad_Y, closed_rad_Z);

And for third, you need to have the global variable for players:

// this will go above main()
new OpenGate[MAX_PLAYERS];

Making automatic gates

Firstly, we will set a timer from OnGameModeInit() which will call after your selected time (mine has checked after 500ms, always). Feel free to change the 500ms to some other amount, but keep in mind that 1000ms equals one second. Learn more about the SetTimer function.

SetTimer("CheckGate", 500, true);

Now, we'll move on to the timer, which we'll forward properly.

// this will go above main()
forward CheckGate();
public CheckGate()
{
    for(new i = 0; i < GetMaxPlayers(); i++)
    {
        if(!IsPlayerConnected(i)) continue;
        if(PlayerToPoint(10.0, i, closed_X, closed_Y, closed_Z) && OpenGate[i] == 0)
        {
            MoveObject(c_gate, open_X, open_Y, open_Z);
            OpenGate[i] = 1;
        }
        else if(!PlayerToPoint(10.0, i, closed_X, closed_Y, closed_Z) && OpenGate[i] == 1)
        {
            MoveObject(c_gate, closed_X, closed_Y, closed_Z);
            OpenGate[i] = 0;
        }
    }
}

There, your gates should be ready, if you've done all that the guide has said, properly.