text
stringlengths 1
2.83M
| id
stringlengths 16
152
| metadata
dict | __index_level_0__
int64 0
949
|
---|---|---|---|
---
title: SendClientMessage
description: Ova funkcija šalje poruku navedenom igraču sa odabranom bojom u chatu.
tags: []
---
## Deskripcija
Ova funkcija šalje poruku navedenom igraču sa odabranom bojom u chatu. Cijela linija u chatboxu će biti u postavljenoj boji sve dok se ne koristi ugrađivanje boja u tekstu.
| Ime | Deskripcija |
| --------------- | --------------------------------------- |
| playerid | ID igrača za prikazati poruku. |
| color | Boja poruke (0xRRGGBBAA Hex format). |
| const message[] | Tekst za prikazati (max 144 karaktera). |
## Returns
1: Funkcija uspješno izvršena. Uspješno je prijavljeno i kada je string veći od 144 karaktera, ali poruka neće biti poslana.
0: Funkcija neuspješno izvršena. Igrač nije konektovan.
## Primjeri
```c
#define COLOR_RED 0xFF0000FF
public OnPlayerConnect(playerid)
{
SendClientMessage(playerid, COLOR_RED, "Ovaj tekst je crven");
SendClientMessage(playerid, 0x00FF00FF, "Ovaj tekst je zelen.");
SendClientMessage(playerid, -1, "Ovaj tekst je bijel.");
return 1;
}
```
## Zabilješke
:::tip
Ugradnju boja možete koristiti za više boja u poruci. Korištenje '-1' kao boje učinit će tekst bijelim (iz jednostavnog razloga što je -1, kada je predstavljen u heksadecimalnom zapisu, 0xFFFFFFFF).
:::
:::warning
Ako je poruka duža od 144 znaka, neće se poslati. Skraćivanje se može koristiti da se to spriječi. Prikazivanje poruke u više redaka također će riješiti ovaj problem. Izbjegavajte upotrebu znaka postotka (ili specifikatora formata) u stvarnom tekstu poruke, a da ga pravilno ne izbjegnete (poput %%). U suprotnom će rezultirati padovima.
:::
## Srodne Funkcije
- [SendClientMessageToAll](SendClientMessageToAll): Pošalji poruku svim igračima.
- [SendPlayerMessageToPlayer](SendPlayerMessageToPlayer): Prisilite igrača da pošalje tekst za jednog igrača.
- [SendPlayerMessageToAll](SendPlayerMessageToAll): Prisilite igrača da pošalje tekst za sve igrače.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SendClientMessage.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SendClientMessage.md",
"repo_id": "openmultiplayer",
"token_count": 897
} | 400 |
---
title: SetMenuColumnHeader
description: Postavlja naslov stupca u meniju.
tags: ["menu"]
---
## Deskripcija
Postavlja naslov stupca u meniju.
| Ime | Deskripcija |
| ------ | ------------------------------------- |
| menuid | ID menija za izmijeniti. |
| column | Stupac (0 ili 1) za postaviti naslov. |
| text[] | Tekst opisa za stupac. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
new Menu: gTestMenu;
// U ovom su meniju dva reda
gTestMenu = CreateMenu("Menu Header", 2, 200.0, 100.0, 150.0, 150.0);
SetMenuColumnHeader(gTestMenu, 0, "Row 1");
SetMenuColumnHeader(gTestMenu, 1, "Row 2");
// Dodajte mu stavke u meniju.
AddMenuItem(gTestMenu, 0, "Row1 Item1");
AddMenuItem(gTestMenu, 1, "Row2 Item1");
```
## Zabilješke
:::tip
Crashuje kada se proslijedi nevažeći ID menija.
:::
:::warning
Imajte na umu da pomoću AddMenuItem možete dodati samo 12 predmeta/stavki. 13. objekt menija zamijenio bi zaglavlje stupca koje je pravilno postavljeno ovom funkcijom.
:::
## Srodne Funkcije
- [AddMenuItem](AddMenuItem): Dodaj artikal u meni.
- [CreateMenu](CreateMenu): Kreiraj meni.
- [OnPlayerSelectedMenuRow](../callbacks/OnPlayerSelectedMenuRow): Pozvano kada igrač odabere red u meniju.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SetMenuColumnHeader.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SetMenuColumnHeader.md",
"repo_id": "openmultiplayer",
"token_count": 574
} | 401 |
---
title: SetPlayerCameraLookAt
description: Postavi smjer u kojem će gledati kamera igrača.
tags: ["player"]
---
## Deskripcija
Postavi smjer u kojem će gledati kamera igrača. Generalno namijenjeno korištenju u kombinaciji s SetPlayerCameraPos.
| Ime | Deskripcija |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | ID player whose camera to set. |
| Float:x | X kordinata na koju će igračeva kamera gledati. |
| Float:y | Y kordinata na koju će igračeva kamera gledati. |
| Float:z | Z kordinata na koju će igračeva kamera gledati. |
| cut | [Stil](../resources/cameracutstyles) promjene. Može se koristiti za interpolaciju (lagana promjena) Od stare do nove pozicije koristeći CAMERA_MOVE. |
## Returns
1: Funkcija uspješno izvršena.
0: Funkcija neuspješno izvršena. Navedeni igrač ne postoji.
## Primjeri
```c
SetPlayerCameraPos(playerid, 320.0, 50.0, 170.0);
SetPlayerCameraLookAt(playerid, 324.34, 54.122, 173.35);
```
## Zabilješke
:::warning
Korištenje funkcija kamere izravno nakon omogućavanja režima spectatora ne radi.
:::
## Srodne Funkcije
- [SetPlayerCameraPos](SetPlayerCameraPos): Postavi poziciju kamere igrača.
- [SetCameraBehindPlayer](SetCameraBehindPlayer): Postavi kameru igrača iza njega.
- [GetPlayerCameraPos](GetPlayerCameraPos): Saznajte gdje je kamera igrača.
- [GetPlayerCameraFrontVector](GetPlayerCameraFrontVector): Dobij prednji vektor kamere igrača.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerCameraLookAt.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerCameraLookAt.md",
"repo_id": "openmultiplayer",
"token_count": 1458
} | 402 |
---
title: SetPlayerObjectMoveSpeed
description: Postavi brzinu kretanja player-objekta.
tags: ["player", "object", "playerobject"]
---
<VersionWarn version='omp v1.1.0.2612' />
## Deskripcija
Postavi brzinu kretanja player-objekta.
| Ime | Deskripcija |
|-------------|-----------------------------------------------------------|
| playerid | ID igrača. |
| objectid | ID player-objekta kojem se seta brzina kretanja. |
| Float:speed | Brzina kojom će se objekat kretati (jedinica u sekundi). |
## Returnovi
`true` - Funkcija uspješno izvršena.
`false` - Funkcija neuspješno izvršena. Navedeni objekat ne postoji.
## Primjeri
```c
new playerobjectid = CreatePlayerObject(playerid, 985, 1003.39154, -643.33423, 122.35060, 0.00000, 1.00000, 24.00000);
MovePlayerObject(playerid, playerobjectid, 1003.3915, -643.3342, 114.5122, 0.8);
SetPlayerObjectMoveSpeed(playerid, playerobjectid, 1.5);
// Brzina kretanja je promijenjena sa 0.8 na 1.5
```
## Srodne Funkcije
- [MovePlayerObject](MovePlayerObject): Pomjeri player objekat na novu poziciju zadanom brzinom.
- [GetPlayerObjectMoveSpeed](GetPlayerObjectMoveSpeed): Dobij brzinu kretanja player-objekta.
- [SetObjectMoveSpeed](SetObjectMoveSpeed): Postavi brzinu kretanja objekta.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerObjectMoveSpeed.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerObjectMoveSpeed.md",
"repo_id": "openmultiplayer",
"token_count": 584
} | 403 |
---
title: SetPlayerWantedLevel
description: Postavi wanted level igrača (6 smeđih zvjetdica ispod HUD-a).
tags: ["player"]
---
## Deskripcija
Postavi wanted level igrača (6 smeđih zvjetdica ispod HUD-a).
| Ime | Deskripcija |
| -------- | --------------------------------------- |
| playerid | ID igrača za postaviti wanted level. |
| level | Wanted level za postaviti igraču (0-6). |
## Returns
1: Funkcija uspješno izvršena.
0: Funkcija neuspješno izvršena. Navedeni igrač ne postoji.
## Primjeri
```c
if (strcmp(cmdtext, "/turnuptheheat", true) == 0)
{
SetPlayerWantedLevel(playerid, 6);
SendClientMessage(playerid, 0xFF0000FF, "Wanted Level: 6");
return 1;
}
```
## Srodne Funkcije
- [GetPlayerWantedLevel](GetPlayerWantedLevel): Provjeri wanted level igrača.
- [PlayCrimeReportForPlayer](PlayCrimeReportForPlayer): Pusti krivičnu prijavu za igrača.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerWantedLevel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SetPlayerWantedLevel.md",
"repo_id": "openmultiplayer",
"token_count": 382
} | 404 |
---
title: SetVehicleParamsForPlayer
description: Postavi parametre vozila za igrača.
tags: ["player", "vehicle"]
---
## Deskripcija
Postavi parametre vozila za igrača.
| Ime | Deskripcija |
| ----------- | --------------------------------------------------------------------------------------------------- |
| vehicle | ID vozila za postaviti parametre. |
| playerid | ID igrača za kojeg treba postaviti parametre vozila. |
| objective | 0 da onemogućite cilj (objective) ili 1 da ga prikažete. Ovo je klimava žuta strelica iznad vozila. |
| doorslocked | 0 za otključati vrata ili 1 da ih zaključate. |
## Returns
1: Funkcija uspješno izvršena.
0: Funkcija neuspješno izvršena. Navedeni igrač i/ili vozilo ne postoje.
## Primjeri
```c
// nekad ranije:
SetVehicleParamsForPlayer(iPlayerVehicle, iPlayerID, 1, 0);
// nekad kasnije kada želite respawnovati auto:
new
iEngine, iLights, iAlarm,
iDoors, iBonnet, iBoot,
iObjective;
GetVehicleParamsEx(iPlayerVehicle, iEngine, iLights, iAlarm, iDoors, iBonnet, iBoot, iObjective);
SetVehicleParamsEx(iPlayerVehicle, iEngine, iLights, iAlarm, iDoors, iBonnet, iBoot, 0);
// Zaključava svoje vozilo za sve igrače, osim igrača koji je koristio komandu.
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext,"/lock",true))
{
if (!IsPlayerInAnyVehicle(playerid)) return SendClientMessage(playerid,0xFFFFFFAA,"Moraš biti unutar vozila.");
for (new i = 0; i < MAX_PLAYERS; i++)
{
if (i == playerid) continue;
SetVehicleParamsForPlayer(GetPlayerVehicleID(playerid),i,0,1);
}
return 1;
}
return 0;
}
// Will show vehicle markers for players streaming in for 0.3a+
new iVehicleObjective[MAX_VEHICLES][2];
public OnGameModeInit() //ili drugi callback
{
new temp = AddStaticVehicleEx(400, 0.0, 0.0, 5.0, 0.0, 0,0, -1); //ID 1
iVehicleObjective[temp][0] = 1; //Marker
iVehicleObjective[temp][1] = 0; //Zaklujčavanje vrata
return 1;
}
stock SetVehicleParamsForPlayerEx(vehicleid, playerid, objective, doorslocked)
{
SetVehicleParamsForPlayer(vehicleid, playerid, objective, doorslocked);
iVehicleObjective[vehicleid][0] = objective;
iVehicleObjective[vehicleid][1] = doorslocked;
}
public OnVehicleStreamIn(vehicleid, forplayerid)
{
SetVehicleParamsForPlayer(vehicleid, forplayerid, iVehicleObjective[vehicleid][0], iVehicleObjective[vehicleid][1]);
}
//Top
new myMarkedCar;
public OnGameModeInit() //Or another callback
{
myMarkedCar = AddStaticVehicleEx(400, 0.0, 0.0, 5.0, 0.0, 0,0, -1); //Npr: Black Landstalker u blizini Blueberry Acres-a
return 1;
}
//Gdje god želite
public OnVehicleStreamIn(vehicleid, forplayerid)
{
if (vehicleid == myMarkedCar)
{
SetVehicleParamsForPlayer(myMarkedCar, forplayerid, 1, 0); // marker može biti vidljiv samo ako je vozilo učitano za igrača
}
return 1;
}
```
## Zabilješke
:::tip
Vozila se moraju respawnovati kako bi se 'objective' uklonio.
:::
:::warning
Od 0.3a verzije morati ćete ponovo primijeniti ovu funkciju kada je OnVehicleStreamIn pozvan.
:::
## Srodne Funkcije
- [SetVehicleParamsEx](SetVehicleParamsEx): Postavlja parametre vozila za sve igrače.
| openmultiplayer/web/docs/translations/bs/scripting/functions/SetVehicleParamsForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/SetVehicleParamsForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1629
} | 405 |
---
title: StopAudioStreamForPlayer
description: Zaustavlja trenutni audio tok za igrača.
tags: ["player"]
---
## Deskripcija
Zaustavlja trenutni audio tok za igrača.
| Ime | Deskripcija |
| -------- | ------------------------------------------------- |
| playerid | Igrač kojem želite zaustaviti trenutni audio tok. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
// Ako igrač napusti vozilo
if (oldstate == PLAYER_STATE_DRIVER || oldstate == PLAYER_STATE_PASSENGER)
{
StopAudioStreamForPlayer(playerid); // Zaustavi audio stream
}
return 1;
}
```
## Srodne Funkcije
- [PlayAudioStreamForPlayer](PlayAudioStreamForPlayer): Reprodukuje audio tok za igrača.
- [PlayerPlaySound](PlayerPlaySound): Reprodukujte zvuk za igrača.
| openmultiplayer/web/docs/translations/bs/scripting/functions/StopAudioStreamForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/StopAudioStreamForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 387
} | 406 |
---
title: TextDrawSetPreviewModel
description: Postavi Model za textdraw prikaz modela.
tags: ["textdraw"]
---
## Deskripcija
Postavi Model za textdraw prikaz modela. Klikni ovdje da vidiš efekat ove funkcije.
| Ime | Deskripcija |
| ---------- | ------------------------------------------ |
| text | ID textdrawa koji će prikazati 3D pregled. |
| modelindex | GTA SA ili SA:MP model ID za prikazati. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
new Text:textdraw;
public OnGameModeInit()
{
textdraw = TextDrawCreate(320.0, 240.0, "_");
TextDrawFont(textdraw, TEXT_DRAW_FONT_MODEL_PREVIEW);
TextDrawUseBox(textdraw, true);
TextDrawBoxColor(textdraw, 0x000000FF);
TextDrawTextSize(textdraw, 40.0, 40.0);
TextDrawSetPreviewModel(textdraw, 411); //Prikaži model 411 (Infernus)
//TextDrawSetPreviewModel(textdraw, 1); //Prikaži model 1 (CJ Skin)
//TextDrawSetPreviewModel(textdraw, 18646); //Prikaži model 18646 (Police light objekat)
//Još uvijek moraš da koristiš TextDrawShowForAll/TextDrawShowForPlayer kako bi textdraw bio vidljiv.
return 1;
}
```
## Zabilješke
:::tip
Koristi [TextDrawBackgroundColor](TextDrawBackgroundColor) da postaviš boju pozadine iza Modela.
:::
:::warning
Textdraw MORA korisiti tip fonta `TEXT_DRAW_FONT_MODEL_PREVIEW` kako bi ova funkcija imala efekta.
:::
## Srodne Funkcije
- [TextDrawSetPreviewRot](TextDrawSetPreviewRot): Postavlja rotaciju 3D prikaza u textdraw-u.
- [TextDrawSetPreviewVehCol](TextDrawSetPreviewVehCol): Postavi boju vozila u 3D pregledu modela textdrawa.
- [TextDrawFont](TextDrawFont): Postavi font textdrawa.
- [PlayerTextDrawSetPreviewModel](PlayerTextDrawSetPreviewModel): Postavlja ID modela 3D prikaza u player-textdrawu.
## Related Callbacks
- [OnPlayerClickTextDraw](../callbacks/OnPlayerClickTextDraw): Pozvano kada igrač klikne na textdraw.
| openmultiplayer/web/docs/translations/bs/scripting/functions/TextDrawSetPreviewModel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/TextDrawSetPreviewModel.md",
"repo_id": "openmultiplayer",
"token_count": 778
} | 407 |
---
title: Update3DTextLabelText
description: Ažurira text i boju 3D Text Labela.
tags: ["3dtextlabel"]
---
## Deskripcija
Ažurira text i boju 3D Text Labela.
| Ime | Deskripcija |
| --------- | ----------------------------------------------- |
| Text3D:textid | 3D Text Label kojeg želite ažurirati. |
| color | Boja 3D Text Labela kojeg će od sada imati. |
| text[] | Novi text kojeg će 3D Text Label od sada imati. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
public OnGameModeInit()
{
new Text3D: mylabel;
mylabel = Create3DTextLabel("Ja sam na kordinatama:\n30.0,40.0,50.0", 0x008080FF, 30.0, 40.0, 50.0, 40.0, 0);
Update3DTextLabelText(mylabel, 0xFFFFFFFF, "New text.");
return 1;
}
```
## Zabilješke
:::warning
Ako je text[] prazan, server/client-i pored texta će možda crashovati.
:::
## Srodne Funkcije
- [Create3DTextLabel](Create3DTextLabel): Kreiraj 3D text label.
- [Delete3DTextLabel](Delete3DTextLabel): Obriši 3D text label.
- [Attach3DTextLabelToPlayer](Attach3DTextLabelToPlayer): Prikvači 3D text label za igrača.
- [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle): Prikvači 3D text label za vozilo.
- [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel): Kreiraj 3D text label za jednog igrača.
- [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel): Obriši igračev 3D text label.
- [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabelText): Promijeni tekst igračevog 3D text labela.
| openmultiplayer/web/docs/translations/bs/scripting/functions/Update3DTextLabelText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/Update3DTextLabelText.md",
"repo_id": "openmultiplayer",
"token_count": 662
} | 408 |
---
title: db_get_field_assoc
description: Dobiva sadržaj polja kao string s navedenim imenom polja.
keywords:
- sqlite
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Dobiva sadržaj polja kao string s navedenim imenom polja.
| Ime | Deskripcija |
| ----------------- | -------------------------------- |
| DBResult:dbresult | Rezultat za dobivanje podataka. |
| field | Indeks polja za dobivanje imena. |
| result[] | Rezultat. |
| maxlength | Maksimalna dužina polja. |
## Returns
Vraća 1 ako je upravitelj skupa rezultata važeći i stupac dostupan, inače 0.
## Primjeri
```c
// examples.inc
// ...
Examples_ListNames(DB:dbConnectionHandle)
{
// Skup rezultata rezultata baze podataka
new DBResult:db_result_set = db_query("SELECT `name` FROM `examples`");
// Ako je zbir rezultata rezultata baze podataka valjan
if (db_result_set)
{
// Allocate some memory to store results
new result[256];
// Radi operacije
do
{
// Dodajte vrijednost iz polja "primjer" u varijablu povratne vrijednosti
db_get_field_assoc(db_result_set, "name", result, sizeof result);
}
// Dok bi se mogao preuzeti sljedeći red
while (db_next_row(db_result_set));
// Oslobodi rezultat
db_free_result(db_result_set);
}
}
```
```c
// mode.pwn
// ...
#include <examples>
static DB:gDBConnectionHandle;
// ...
public OnGameModeInit()
{
// ...
// Kreiramo konekciju za databazu
gDBConnectionHandle = db_open("example.db");
// Ako konekcija za databazu postoji
if (gDBConnectionHandle)
{
// Uspješno kreirana konekcija do databaze
print("Uspješno stvorena veza s bazom podataka \"example.db\".");
Examples_ListNames(gDBConnectionHandle);
}
else
{
// Neuspješno kreirana konekcija do databaze
print("Otvaranje veze s bazom podataka nije uspjelo \"example.db\".");
}
// ...
return 1;
}
public OnGameModeExit()
{
// Zatvori konekciju sa databazom ako je otvorena
if (db_close(gDBConnectionHandle))
{
// Dodatno čišćenje
gDBConnectionHandle = DB:0;
}
// ...
return 1;
}
```
## Zabilješke
:::warning
Upotreba nevaljanog upravitelja databaze koja nije nula srušit će vaš server! Nabavite važeći upravitelj databazom pomoću [db_open] (db_open).
:::
## Srodne Funkcije
- [db_open](db_open): Otvori konekciju do SQLite databaze.
- [db_close](b_close): Zatvori konekciju do SQLite databaze.
- [db_query](db_query): Upitajte SQLite bazu podataka.
- [db_free_result](db_free_result): Oslobodite memoriju rezultata iz db_query.
- [db_num_rows](db_num_rows): Dobijte broj redaka u rezultatu.
- [db_next_row](db_next_row): Pređi na sljedeći red.
- [db_num_fields](db_num_fields): Dobij broj polja u rezultatu.
- [db_field_name](db_field_name): Return/vraća ime polja na posebnom indexu.
- [db_get_field](db_get_field): Preuzmite sadržaj polja iz db_query.
- [db_get_field_int](db_get_field_int): Dobijte sadržaj polja kao cijeli broj iz db_query.
- [db_get_field_assoc_int](db_get_field_assoc_int): Dobijte sadržaj polja kao cijeli broj s navedenim imenom iz trenutnog reda rezultata.
- [db_get_field_float](db_get_field_float): Dobijte sadržaj polja kao float broj s navedenim imenom iz trenutnog reda rezultata.
- [db_get_field_assoc_float](db_get_field_assoc_float): Dobij sadržaj polja kao float broj s navedenim imenom polja.
- [db_get_mem_handle](db_get_mem_handle): Dobij memorijski upravitelj za vezu SQLite databaze koja je otvorena s `db_open`.
- [db_get_result_mem_handle](db_get_result_mem_handle): Dobiva memorijski upravitelj za vezu SQLite databaze koja je dodijeljena sa s `db_query`.
- [db_debug_openfiles](db_debug_openfiles): Dobiva broj otvorenih konekcija/veza databaza u svrhu otklanjanja pogrešaka.
- [db_debug_openresults](db_debug_openresults): Dobiva broj rezultata otvorene databaze.
| openmultiplayer/web/docs/translations/bs/scripting/functions/db_get_field_assoc.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/db_get_field_assoc.md",
"repo_id": "openmultiplayer",
"token_count": 1891
} | 409 |
---
title: fclose
description: Zatvara fajl/datoteku.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Zatvara fajl/datoteku. Fajlove/Datoteke treba uvijek zatvoriti kada ih skripta više ne treba (nakon čitanja / pisanja).
| Ime | Deskripcija |
| ----------- | ------------------------------------------------------------- |
| File:handle | Upravitelj datoteke za zatvoriti. Returnovan/vraćen od fopen. |
## Returns
1: Funkcija uspješno izvršena.
0: Funkcija neuspješno izvršena. Datoteka/fajl se ne može zatvoriti. Možda je već zatvorena.
## Primjeri
```c
// Otvorite "file.txt" u "append only" načinu (samo dodavanje)
new File:handle = fopen("file.txt", io_append);
// Provjeri da li je fajl/datoteka otvoren/a
if (handle)
{
// Uspješno
// Ispiši "Hi there!" u fajl/datoteku
fwrite(handle, "Hi there!");
// Zatvori fajl/datoteku
fclose(handle);
}
else
{
// Error
print("Nesupješno otvaranje file \"file.txt\".");
}
```
## Zabilješke
:::warning
Korištenje nevaljanog upravitelja srušit će vaš server! Nabavite važeći upravitelj pomoću fopen ili ftemp.
:::
## Srodne Funkcije
- [fopen](fopen): Otvori fajl/datoteku.
- [ftemp](ftemp): Stvorite privremeni tok fajlova/datoteka.
- [fremove](fremove): Uklonite fajl/datoteku.
- [fwrite](fwrite): Piši u fajl/datoteku.
- [fread](fread): Čitaj fajl/datoteku.
- [fputchar](fputchar): Stavite znak u fajl/datoteku.
- [fgetchar](fgetchar): Dobijte znak iz fajla/datoteke.
- [fblockwrite](fblockwrite): Zapišite blokove podataka u fajl/datoteku.
- [fblockread](fblockread): Očitavanje blokova podataka iz fajla/datoteke.
- [fseek](fseek): Skoči na određeni znak u fajlu/datoteci.
- [flength](flength): Nabavite dužinu fajla/datoteke.
- [fexist](fexist): Provjeri da li datoteka postoji.
- [fmatch](fmatch): Provjeri podudaraju li se uzorci s nazivom datoteke.
| openmultiplayer/web/docs/translations/bs/scripting/functions/fclose.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/fclose.md",
"repo_id": "openmultiplayer",
"token_count": 914
} | 410 |
---
title: floatsqroot
description: Izračunava kvadratni korijen zadate vrijednosti.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Izračunava kvadratni korijen zadate vrijednosti.
| Ime | Deskripcija |
| ----- | ------------------------------------------------ |
| value | Vrijednost za izračunavanje kvadratnog korijena. |
## Returns
Kvadratni korijen ulazne vrijednosti, kao float.
## Primjeri
```c
floatsqroot(25.0); // Vraća 5, zato što je 5x5 = 25
```
## Zabilješke
:::tip
Ova funkcija dovodi do greške "domene" ako je ulazna vrijednost negativna. Možete koristiti floatabs da biste dobili apsolutnu (pozitivnu) vrijednost.
:::
## Srodne Funkcije
- [floatpower](floatpower): Povećava zadanu vrijednost u stepen eksponenta.
- [floatlog](floatlog): Nabavite logaritam plutajuće vrijednosti.
| openmultiplayer/web/docs/translations/bs/scripting/functions/floatsqroot.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/floatsqroot.md",
"repo_id": "openmultiplayer",
"token_count": 422
} | 411 |
---
title: getproperty
description: Uzmite određenu imovinu iz memorije, string se vraća kao spakirani string!
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Uzmite određenu imovinu iz memorije, string se vraća kao spakirani string!
| Ime | Deskripcija |
| -------- | ------------------------------------------------------------------------------- |
| id | Virtualna mašina za upotrebu, trebali biste zadržati ovu nulu. |
| name[] | Ime imovine, trebali biste ovo zadržati "". |
| value | Jedinstveni ID imovine, upotrijebite hash-funkciju za izračunavanje iz stringa. |
| string[] | Varijabla za pohraniti rezultat, proslijeđeno referencom. |
## Returns
Vrijednost imovine kada se prenese ime; popunjava argument niza kada se vrijednost preda. Ako imovina ne postoji, ova funkcija vraća nulu.
## Primjeri
```c
new value[16];
getproperty(0, "", 123984334, value);
strunpack(value, value, sizeof(value));
print(value);
```
## Zabilješke
:::tip
Preporučljivo je da koristite PVars/SVars ili GVar plugin umjesto ovih native-a zbog njihove brzine (spori su).
:::
## Srodne Funkcije
- [setproperty](setproperty): Postavi imovinu.
- [deleteproperty](deleteproperty): Obriši imovinu.
- [existproperty](existproperty): Provjeri da li imovina postoji.
| openmultiplayer/web/docs/translations/bs/scripting/functions/getproperty.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/getproperty.md",
"repo_id": "openmultiplayer",
"token_count": 679
} | 412 |
---
title: setarg
description: Postavite argument koji je proslijeđen funkciji.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Postavite argument koji je proslijeđen funkciji.
| Ime | Deskripcija |
| ----- | ---------------------------------------------------- |
| arg | Broj sekvence argumenta. Koristi 0 za prvi argument. |
| index | Index (ako je argument niz/array). |
| value | Vrijednost na koju treba postaviti argument. |
## Returns
[edit]
## Srodne Funkcije
- [getarg](getarg): Dohvaćanje argumenta iz liste argumenata varijable.
- [numargs](numargs): Vrati broj argumenata.
| openmultiplayer/web/docs/translations/bs/scripting/functions/setarg.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/setarg.md",
"repo_id": "openmultiplayer",
"token_count": 303
} | 413 |
---
title: uuencode
description: Kodirajte string u UU dekodirani string.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Kodirajte string u UU dekodirani string.
| Ime | Deskripcija |
| -------------- | --------------------------------------------------------- |
| dest[] | Odredišni string za kodirani tok. |
| const source[] | Izvor, nekodirani string. |
| numbytes | Broj bajtova za kodiranje, ovaj ne smije biti veći od 45. |
| maxlength | Maksimalna dužina dest[] niza. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
uuencode(encodedString, normalString, 45);
```
## Srodne Funkcije
- [Uudecode](Uudecode): Dekodirajte UU kodirani string.
- [Memcpy](Memcpy): Kopirajte bajtove s jedne lokacije na drugu.
| openmultiplayer/web/docs/translations/bs/scripting/functions/uuencode.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/uuencode.md",
"repo_id": "openmultiplayer",
"token_count": 486
} | 414 |
---
title: Client
description: Dieser Bereich beinhaltet Informationen über den SA-MP Client und Support.
---
Dieser Bereich beinhaltet Informationen über den SA-MP Client und Support.
| openmultiplayer/web/docs/translations/de/client/_.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/de/client/_.md",
"repo_id": "openmultiplayer",
"token_count": 59
} | 415 |
---
título: OnIncomingConnection
descripción: Este callback se llama cuando una dirección IP intenta establecer una conexión con el servidor.
tags: []
---
## Descripción
Este callback se llama cuando una dirección IP intenta establecer una conexión con el servidor. Para bloquear conexiones entrantes, use BlockIpAdress.
| Nombre | Descripción |
| ------------ | -------------------------------------------------- |
| playerid | El ID del jugador que está intentando conectarse. |
| ip_address[] | La IP del jugador que está intentando conectarse. |
| port | El puerto de la conexión intentada. |
## Devoluciones
1 - Prevendrá a otros filterscripts de recibir este callback.
0 - Indica que este callback será pasado al siguiente filterscript.
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnIncomingConnection(playerid, ip_address[], port)
{
printf("Conexión entrante del jugador ID %i [IP/puerto: %s:%i]", playerid, ip_address, port);
return 1;
}
```
## Funciones Relacionadas
- [BlockIpAddress](../functions/BlockIpAddress): Bloquea una dirección IP de conectarse al servidor por un tiempo determinado.
- [UnBlockIpAddress](../functions/UnBlockIpAddress): Desbloquea una IP que fue anteriormente bloqueada.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnIncomingConnection.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnIncomingConnection.md",
"repo_id": "openmultiplayer",
"token_count": 510
} | 416 |
---
título: OnPlayerExitVehicle
descripción: Este callback se llama cuando un jugador comienza a salir de un vehículo.
tags: ["player", "vehicle"]
---
## Descripción
Este callback se llama cuando un jugador comienza a salir de un vehículo.
| Nombre | Descripción |
| --------- | ---------------------------------------------------- |
| playerid | El ID del jugador que está saliendo de un vehículo. |
| vehicleid | El ID del vehículo del que el jugador está saliendo. |
## Devoluciones
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnPlayerExitVehicle(playerid, vehicleid)
{
new string[35];
format(string, sizeof(string), "INFORMACIÓN: Estás saliendo del vehículo %i", vehicleid);
SendClientMessage(playerid, 0xFFFFFFFF, string);
return 1;
}
```
## Notas
:::warning
No se llama si el jugador se cae de una moto o es removido del vehículo por otros medios como usando SetPlayerPos. Debes usar OnPlayerStateChange y comprobar si su estado anterior es PLAYER_STATE_DRIVER o PLAYER_STATE_PASSENGER y su nuevo estado es PLAYER_STATE_ONFOOT.
:::
## Funciones Relacionadas
- [RemovePlayerFromVehicle](../functions/RemovePlayerFromVehicle): Sacar a un jugador de un vehículo.
- [GetPlayerVehicleSeat](../functions/GetPlayerVehicleSeat): Comprobar en qué asiento está un jugador.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerExitVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerExitVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 515
} | 417 |
---
título: OnPlayerSpawn
descripción: Este callback se llama cuando un jugador spawnea.
tags: ["player"]
---
## Descripción
Este callback se llama cuando un jugador spawnea. (ej. después de llamar la función SpawnPlayer)
| Nombre | Descripción |
| -------- | ---------------------------------- |
| playerid | El ID del jugador que spawneó. |
## Devoluciones
1 - Prevendrá a otros filterscripts de recibir este callback.
0 - Indica que este callback será pasado al siguiente filterscript.
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnPlayerSpawn(playerid)
{
new PlayerName[MAX_PLAYER_NAME],
string[40];
GetPlayerName(playerid, PlayerName, sizeof(PlayerName));
format(string, sizeof(string), "%s spawneó correctamente.", PlayerName);
SendClientMessageToAll(0xFFFFFFFF, string);
return 1;
}
```
## Notas
:::tip
El juego algunas veces le saca \$100 a los jugadores después de spawnear.
:::
## Funciones Relacionadas
- [SpawnPlayer](../functions/SpawnPlayer): Forzar a un jugador a spawnear.
- [AddPlayerClass](../functions/AddPlayerClass): Añadir una clase.
- [SetSpawnInfo](../functions/SetSpawnInfo): Establecer la configuración de spawn a un jugador.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 458
} | 418 |
---
título: OnVehiclePaintjob
descripción: Se llama cuando un jugador obtiene una vista previa de una capa de pintura adentro de un taller de modificación.
tags: ["vehicle"]
---
## Descripción
Se llama cuando un jugador obtiene una vista previa de una capa de pintura adentro de un taller de modificación. Cuidado, este callback no se llama cuando el jugador compra la capa de pintura.
| Nombre | Descripción |
| ---------- | ---------------------------------------------------------------- |
| playerid | El ID del jugador que cambió la capa de pintura. |
| vehicleid | El ID del vehículo al que cambiaron de capa de pintura. |
| paintjobid | El ID de la nueva capa de pintura. |
## Devoluciones
1 - Prevendrá a otros filterscripts de recibir este callback.
0 - Indica que este callback será pasado al siguiente filterscript.
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnVehiclePaintjob(playerid, vehicleid, paintjobid)
{
new string[128];
format(string, sizeof(string), "Cambiaste la capa de pintura de tu vehículo a %d!", paintjobid);
SendClientMessage(playerid, 0x33AA33AA, string);
return 1;
}
```
## Notas
:::tip
Este callback no se llama por ChangeVehiclePaintJob. Puede usar OnVehicleChangePaintjob desde Vsync para saber cuándo el jugador compra el trabajo de pintura.
:::
## Funciones Relacionadas
- [ChangeVehiclePaintjob](../functions/ChangeVehiclePaintjob): Cambiar la capa de pintura de un vehículo.
- [ChangeVehicleColor](../functions/ChangeVehicleColor): Establecer el color de un vehículo.
- [OnVehicleRespray](OnVehicleRespray): Se llama cuando un vehículo es repintado.
- [OnVehicleMod](OnVehicleMod): Se llama cuando un vehículo es modificado.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnVehiclePaintjob.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnVehiclePaintjob.md",
"repo_id": "openmultiplayer",
"token_count": 707
} | 419 |
---
title: OnGameModeInit
description: این کالبک با استارت شدن gamemode فعال می شود.
tags: []
---
<div dir="rtl" style={{ textAlign: "right" }}>
## توضیحات
این کالبک با استارت شدن gamemode فعال می شود.
## مثال ها
</div>
```c
public OnGameModeInit()
{
print("Gamemode start shod!");
return 1;
}
```
<div dir="rtl" style={{ textAlign: "right" }}>
## نکته ها
:::tip
این تابع همچنین میتواند در یک فیلتر اسکریپت مورد استفاده قرار گیرد تا تشخیص دهد که حالت gamemode با دستورات
مانند changemode یا gmx تغییر می کند، زیرا تغییر gamemode باعث بارگیری مجدد فیلتر اسکریپت نمی شود.
:::
## تابع های مرتبط
</div> | openmultiplayer/web/docs/translations/fa/scripting/callbacks/OnGameModeInit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fa/scripting/callbacks/OnGameModeInit.md",
"repo_id": "openmultiplayer",
"token_count": 476
} | 420 |
---
id: Style
title: "Pawn Style Guide"
description: A short guide on the generally accepted naming conventions and other aspects of Pawn source code to aid easier communication of intent and streamline debugging and sharing of code.
---
Ang documentation na ito a maikli lang para sa general accepted naming convensions (Please sumunod sa mga naming convensions para madali matrack ang mga variables or macros mo) at iba
Tignan den ang mga ito:
- [Modern Pawn](https://github.com/Southclaws/sampctl/wiki/Modern-Pawn)
- [Pawn Package](https://github.com/Southclaws/sampctl/wiki/Packages)
## Terminology
### Statement
Ang `statement` ay isang pirasong code na nagsasabi sa host program na gawen ang isang bagay. And `statement` ay isang valid na pirasong code na naghahawak ng isang result/resulta.
```c
a = b + c;
```
Eto ang isang statement na kinokompose ng variable na nakaassign dito ang isang resulta na tinatawag na [#Expression]
```c
SetPlayerColor(playerid, 0xFF4700FF);
```
Eto ay statement na nagsasabi sa program na tumawag ng function na may arugmento.
```c
x + 8
```
Ang isang to ay _HINDI_ statement kasi yung resulta ay hindi naman ginagamit kahit saan, eto ay isang [#Expression] lamang.
### Compound Statement
Ang compound statement ay isang collection ng mga statements na pinapalibutan ng braces
```c
new message[] = "Magandang Umaga!";
print(message);
```
Eto ay isang compound statement na kinokompose ng dalawang statement.
```c
if (a == b)
{
print("Kamusta ka?");
}
```
Eto ay isang compound statement na may `if` condition, eto ay usually na tinatawag na "if statement".
```c
return Function1(), Function2(), Function3();
```
Eto ay _HINDI_ compound statement, eto ay chain ng statements na pinag hihiwalay ng commas `,`, Eto ay form ng chaining statements ay kinokonsinderang bad practice para sa mga baguhan sa Pawn.
### Expression
Ang expression ay isang pirasong syntax na naghahawak ng value/halaga, Eto ay hindi valid statement unless ang tagapaghawak na value ay ginamit sa ibang pamamaraan.
Expressions ay madalas na kinokompose para makabuo ng statements.
```c
a + b
```
Eto ay isang madaling addition expression na kumukuha ng dalawang values/halaga at inaapply ang add operator sakanila.
## Guidelines
### Braces
Allman braces ay recomendado:
```pawn
function()
{
//
}
```
Sapagkat, kung di kaya ng muscle memory mo, K&R braces ay pwede rin sa Pawn:
```pawn
function() {
//
}
```
### Switches
Switches ay dapat merong dalawang indent levels, isa para sa `switch` block at yung isa ay para sa bawa `case` statement o compound statement.
```pawn
switch (variable)
{
case 0:
return 0;
case 1:
return 1;
case 2:
return 2;
default:
return -1;
}
```
```pawn
switch (variable)
{
case 0:
{
// code...
return 0;
}
case 1:
{
// code...
return 1;
}
case 2:
{
// code...
return 2;
}
default:
{
// code...
return -1;
}
}
```
### Compound Statements (Blocks)
Blocks ay dapat palaging gumagamit ng braces, kahit eto ay isang line of code lang ang nag-eexist sa block. Eto ay nag-aapply sa lahat ng level kahit eto pa ay function.
```pawn
func()
{
singleLineExpr();
}
```
```pawn
func()
{
if ()
{
singleLineExpr();
}
}
```
```pawn
func()
{
if ()
{
singleLineExpr();
}
else if ()
{
//
}
else
{
//
}
}
```
### Naming
(Utang na loob please gumamit kayo neto).
### Functions
Functions ay dapat gumamit ng `PascalCase`.
### Global Variables
Global variables declared gamit ang `new` dapat ay palaging merong `g~` prefixed PascalCase. example ay `new g_VariableName`, Pero kung ikaw ay gumamit ng `static` eto ay dapat merong `s_` prefixed PascalCase, example `static s_VariableName`
Constant globals ay dapat gumamit ng `SCREAMING_SNAKE_CASE`.
#### Local Variables
Local variables ay dapat palaging gumamit ng `camelCase` at dapat wag na wag kang gumamit ng single letter names, except sa:
- `i`, `j`, `k`, eto para sa `for` loops.
- `x`, `y`, `z`, etc para sa mathematical contexts
#### Enumerators
Enumerators, kung pangalan, ay dapat gumamit ng prefix na `E_` (isang strong tag) or `e_` (isang weak tag)
Enumerator fields ay dapat `SCREAMING_SNAKE_CASE` at ang gamit ng enumerator name para sa prefix.
```pawn
static enum E_PLAYER_DATA
{
E_PLAYER_CASH,
Float:E_PLAYER_HEALTH,
}
```
Paggumamit ng weak tag
```pawn
static enum e_PLAYER_DATA
{
E_PLAYER_CASH,
Float:E_PLAYER_HEALTH,
}
```
Non-named enumerator fields ay dapat ding `SCREAMING_SNAKE_CASE` at dapat ginagamit ang enumerator name as a prefix.
```pawn
static enum
{
ENUMATOR_INTEGER,
Float:ENUMATOR_FLOAT,
}
```
Enumerators ay dapat palaging declared `static`
except ay gagamitin eto sa labas ng module.
#### Macros and Pre-Processor Definitions
Macros ay dapat palaging gumamit ng `SCREAMING_SNAKE_CASE` regardless sa paggamit nila.
Pre-Processor definitions (constant definitions)
ay dapat gumagamit ng `SCREAMING_SNAKE_CASE`.
Eto ay makakatulong idifferentiate sa pagitan ng variables at constants included dito ang functions at macros.
Eto ay generally advised para maiwasan ang paggawa ng syntactical elements para maprevent ang confusion para sa newcomers as to which words ay parte ng language (Pawn) at which words ay galing sa libraries (Mga nadodownload na .inc).
Pero, ang ibang matatandang libraries ginagawa to at hindi nila mabago dahil sa backwards compatibility.
### Documentation
Palaging document exported functions na may simpleng linya comment sa format `// FunctionName does X, Y and Z and returns A` saan ang unang word ay ang pangalan ng function itself kasunod ang description na ano ang ginagawa netong function na it. Hindi na kelangan magsayang ng oras sapagdedescribe para sa bawat individual parameter.
Example:
```pawn
// LoadPlayerAccount is called to initiate the account load process. This
// function will trigger HTTP calls to get player data, it will display dialogs
// to the player and eventually, once the process has completed, the event
// `OnPlayerLogin` is emitted on success. On failure, the player is kicked.
stock Error:LoadPlayerAccount(playerid)
{
// code...
}
```
Bawat package ay dapat merong `README.md` at, kung necessary, bawat isang module ay dapat merong comment sa pinaka unang line na nagdedescribe na anong mga pwede ibigay ng module na to.
Ikaw ay binabati ko at ikaw ay meron nang alam tungkol sa Pawn language. | openmultiplayer/web/docs/translations/fil/scripting/Language/Style.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/Language/Style.md",
"repo_id": "openmultiplayer",
"token_count": 2411
} | 421 |
---
title: OnNPCModeExit
description: Tinatawag ang callback na ito kapag nag-unload ang isang NPC script.
tags: ["npc"]
---
## Description
Tinatawag ang callback na ito kapag nag-unload ang isang NPC script.
## Examples
```c
public OnNPCModeExit()
{
print("NPC script unloaded");
return 1;
}
```
## Related Callbacks
Maaaring maging kapaki-pakinabang ang mga sumusunod na callback, dahil nauugnay ang mga ito sa callback na ito sa isang paraan o iba pa.
- [OnNPCModeInit](OnNPCModeInit): Tinatawag ang callback na ito kapag nag-load ang isang NPC script. | openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnNPCModeExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnNPCModeExit.md",
"repo_id": "openmultiplayer",
"token_count": 213
} | 422 |
---
title: OnPlayerStateChange
description: This callback is called when a player changes state.
tags: ["player"]
---
## Paglalarawan
Ang callback na ito ay tinatawag kapag ang isang player ay nagbago ng estado. Halimbawa, kapag ang isang manlalaro ay nagbago mula sa pagiging driver ng isang sasakyan patungo sa pagiging on-foot.
| Name | Description |
| -------- | ---------------------------------------- |
| playerid | Ang ID ng player na nagbago ng estado. |
| newstate | Ang bagong estado ng manlalaro. |
| oldstate | Ang dating estado ng manlalaro. |
Sumangguni sa [Player States](../resources/playerstates) para sa listahan ng lahat ng available na estado ng manlalaro.
## Returns
Lagi itong na tatawag una sa mga filterscript.
## Halimbawa ng Paggamit
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
if (oldstate == PLAYER_STATE_ONFOOT && newstate == PLAYER_STATE_DRIVER) // Ang manlalaro ay pumasok sa isang sasakyan bilang isang driver
{
new vehicleid = GetPlayerVehicleID(playerid);
AddVehicleComponent(vehicleid, 1010); // Maglagay ng NOS sa sasakyan
}
return 1;
}
```
## Mga Dapat Unawain
<TipNPCCallbacks />
## Mga Kaugnay na Callbacks
Maaaring maging kapaki-pakinabang ang mga sumusunod na callback, dahil nauugnay ang mga ito sa callback na ito sa isang paraan o iba pa.
- [OnPlayerInteriorChange](./OnPlayerInteriorChange): Tinatawag ang callback na ito kapag nagpalit ng interior ang isang player.
## Mga Kaugnay na Functions
Maaaring maging kapaki-pakinabang ang mga sumusunod na function, dahil nauugnay ang mga ito sa callback na ito sa isang paraan o iba pa.
- [GetPlayerState](../functions/GetPlayerState): Kunin ang kasalukuyang estado ng isang manlalaro.
- [GetPlayerSpecialAction](../functions/GetPlayerSpecialAction): Kumuha ng kasalukuyang espesyal na aksyon ng manlalaro.
- [SetPlayerSpecialAction](../functions/SetPlayerSpecialAction): Magtakda ng espesyal na aksyon ng manlalaro.
| openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerStateChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerStateChange.md",
"repo_id": "openmultiplayer",
"token_count": 765
} | 423 |
---
title: AllowInteriorWeapons
description: I-toggle kung pinapayagan o hindi ang paggamit ng mga armas sa interior.
tags: []
---
## Description
I-toggle kung pinapayagan o hindi ang paggamit ng mga armas sa interior.
| Name | Description |
| ----- | ------------------------------------------------------------------------------------------------------------------------------ |
| allow | 1 upang paganahin ang mga armas sa mga interior (naka-enable bilang default), 0 upang i-disable ang mga armas sa mga interior. |
## Returns
Ang function na ito ay hindi nagbabalik ng anumang partikular na halaga.
## Examples
```c
public OnGameModeInit()
{
// Papayagan nito ang mga armas sa loob ng interior.
AllowInteriorWeapons(1);
return 1;
}
```
## Notes
:::warning
Hindi gumagana ang function na ito sa kasalukuyang bersyon ng SA:MP!
:::
## Related Functions
- [SetPlayerInterior](SetPlayerInterior): Magtakda ng interior ng player.
- [GetPlayerInterior](GetPlayerInterior): Kunin ang kasalukuyang interior ng isang player.
- [OnPlayerInteriorChange](../callbacks/OnPlayerInteriorChange): Tinatawag kapag nagpalit ng interior ang isang player. | openmultiplayer/web/docs/translations/fil/scripting/functions/AllowInteriorWeapons.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/AllowInteriorWeapons.md",
"repo_id": "openmultiplayer",
"token_count": 475
} | 424 |
---
title: ConnectNPC
description: Ikonekta ang isang NPC sa server.
tags: ["npc"]
---
## Description
Ikonekta ang isang NPC sa server.
| Name | Description |
| -------- | ---------------------------------------------------------------------------------------- |
| name[] | Ang pangalan na dapat ikonekta ng NPC bilang. Dapat sundin ang parehong mga patakaran tulad ng mga karaniwang pangalan ng player.|
| script[] | Ang pangalan ng script ng NPC na matatagpuan sa folder ng npcmodes (nang walang extension na .amx).|
## Returns
Ang function na ito ay palaging nag rereturn ng 1.
## Examples
```c
public OnGameModeInit()
{
ConnectNPC("[BOT]Pilot", "pilot");
return 1;
}
```
## Notes
:::tip
Ang mga NPC ay walang mga nametag. Maaaring i-script ang mga ito gamit ang Attach3DTextLabelToPlayer.
:::
## Related Functions
- [IsPlayerNPC](IsPlayerNPC): Suriin kung ang isang player ay isang NPC o isang aktwal na player.
- [OnPlayerConnect](../callbacks/OnPlayerConnect): Tinatawag kapag kumonekta ang isang player sa server. | openmultiplayer/web/docs/translations/fil/scripting/functions/ConnectNPC.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/ConnectNPC.md",
"repo_id": "openmultiplayer",
"token_count": 433
} | 425 |
---
title: GetPlayerScore
description: Ni-rereturn ng function na ito ang score ng isang player gaya ng pagkakatakda nito gamit ang SetPlayerScore.
tags: ["player"]
---
## Description
Ni-rereturn ng function na ito ang score ng isang player gaya ng pagkakatakda nito gamit ang SetPlayerScore.
| Name | Description |
| -------- | ------------------------------- |
| playerid | Ang player na kukunin ang score |
## Returns
Ang score ng player.
## Examples
```c
public OnPlayerCommandText(playerid,text[])
{
if (!strcmp(cmdtext,"/score",true))
{
new string[128];
format(string, sizeof(string), "Score: %i", GetPlayerScore(playerid));
SendClientMessage(playerid, COLOR_ORANGE, string);
return 1;
}
return 0;
}
```
## Related Functions
- [SetPlayerScore](SetPlayerScore): I-set ang score ng isang player.
- [GetPlayerPing](GetPlayerPing): Kunin ang ping ng isang player. | openmultiplayer/web/docs/translations/fil/scripting/functions/GetPlayerScore.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/GetPlayerScore.md",
"repo_id": "openmultiplayer",
"token_count": 339
} | 426 |
---
title: SetPlayerTeam
description: Itakda ang koponan ng isang manlalaro.
tags: ["player"]
---
## Description
Itakda ang koponan ng isang manlalaro.
| Name | Description |
| -------- | ------------------------------------------------------------------------------ |
| playerid | Ang ID ng player na gusto mong itakda ang koponan. |
| teamid | Ang koponan na ilalagay ang manlalaro. Gamitin ang NO_TEAM upang alisin ang manlalaro mula sa anumang koponan. |
## Returns
Ang function na ito ay hindi nagbabalik ng anumang value.
## Examples
```c
public OnPlayerSpawn(playerid)
{
// Itakda ang koponan ng isang manlalaro sa 4 kapag sila ay nangitlog
SetPlayerTeam(playerid, 4);
return 1;
}
```
## Notes
:::tip
Ang mga manlalaro ay hindi maaaring makapinsala/makapatay ng mga manlalaro sa parehong koponan maliban kung gagamit sila ng kutsilyo upang laslasin ang kanilang lalamunan. Sa SA-MP 0.3x, ang mga manlalaro ay hindi rin makakasira ng mga sasakyang minamaneho ng isang manlalaro mula sa parehong koponan. Maaari itong paganahin sa EnableVehicleFriendlyFire. Ang 255 (o NO_TEAM) ay ang default na koponan na makakapag-shoot ng iba pang mga manlalaro, hindi 0.
:::
## Related Functions
- [GetPlayerTeam](GetPlayerTeam): Suriin kung nasaang koponan ang isang manlalaro.
- [SetTeamCount](SetTeamCount): Itakda ang bilang ng mga team na available.
- [EnableVehicleFriendlyFire](EnableVehicleFriendlyFire): I-enable ang friendly fire para sa mga sasakyan ng team. | openmultiplayer/web/docs/translations/fil/scripting/functions/SetPlayerTeam.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/SetPlayerTeam.md",
"repo_id": "openmultiplayer",
"token_count": 638
} | 427 |
---
title: floatcos
description: Kunin ang cosine mula sa isang naibigay na anggulo.
tags: ["math", "floating-point"]
---
<LowercaseNote />
## Description
Kunin ang cosine mula sa isang naibigay na anggulo. Ang input angle ay maaaring nasa radians, degrees o grades.
| Name | Description |
| ----------- | ------------------------------------------------------ |
| Float:value | Ang anggulo kung saan makukuha ang cosine. |
| anglemode | Ang [angle mode](../resources/anglemodes) na gagamitin, depende sa value na ipinasok. |
## Returns
Ang cosine ng value na ipinasok.
## Examples
```c
public OnGameModeInit()
{
printf("The cosine from 90° is %f", floatcos(90.0, degrees));
// Output: 0
return 1;
}
```
## Notes
:::warning
Gumagamit ang GTA/SA-MP ng mga degree para sa mga anggulo sa karamihan ng mga pangyayari, halimbawa [GetPlayerFacingAngle](GetPlayerFacingAngle). Samakatuwid, malamang na gugustuhin mong gamitin ang 'degrees' angle mode, hindi radians. Tandaan din na ang mga anggulo sa GTA ay counterclockwise; 270° ay Silangan at 90° ay Kanluran. Ang timog ay 180° pa rin at ang Hilaga ay 0°/360° pa rin.
:::
## Related Functions
- [floatsin](floatsin): Kunin ang sine mula sa isang tiyak na anggulo.
- [floattan](floattan): Kunin ang tangent mula sa isang tiyak na anggulo. | openmultiplayer/web/docs/translations/fil/scripting/functions/floatcos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/floatcos.md",
"repo_id": "openmultiplayer",
"token_count": 524
} | 428 |
---
title: Ressources
description: Liste exhaustive d'outils, de librairies et de plugins SA:MP nécessaires au développement d'un serveur.
---
## Outils
- **[Community Compiler](https://github.com/pawn-lang/compiler/)** - Une version mise à jour du compilateur, avec de nombreux correctifs et améliorations.
- **[sampctl](http://sampctl.com/)** - Gestionnaire de packages pour installer des bibliothèques et exécuter votre serveur.
- **[Plugin Runner](https://github.com/Zeex/samp-plugin-runner/)** - Outil pour exécuter une version allégée du serveur via les lignes de commande (pas de server.cfg requis) pour tester les plugins.
- **[Pawn Syntax - Sublime](https://packagecontrol.io/packages/Pawn%20syntax/)** - Autocomplétion PAWN sur Sublime Text 3.
- **[Pawn Syntax - Visual Marketplace](https://marketplace.visualstudio.com/items?itemName=southclaws.vscode-pawn/)** - Autocomplétion PAWN sur Visual Studio.
- **[SA-MP Zone Editor](https://bitbucket.org/Grimrandomer/samp-zone-editor/downloads/)** - Zone Editor pour créer des areas.
- **[SA-MP Map Editor](https://github.com/openmultiplayer/archive/raw/master/tools/Map%20Editor.zip)** - Map Editor populaire pour SA:MP.
## Librairies
- **[SA:MP stdlib](https://github.com/pawn-lang/samp-stdlib/)** - `const`-corrigé, documenté, et complété.
- **[fixes.inc](https://github.com/pawn-lang/sa-mp-fixes/)** - Corrige de nombreux bugs intrinsèques à SA:MP.
- **[YSI](https://github.com/pawn-lang/YSI-Includes/)** - La bibliothèque la plus ancienne, la plus vaste, la plus testée et la mieux prise en charge pour SA: MP / pawn, offrant un grand nombre de nouvelles fonctionnalités de jeu et de développement PAWN.
- **[amx_assembly](https://github.com/Zeex/amx_assembly/)**
- **[indirection](https://github.com/Y-Less/indirection/)** - Système pour utiliser les pointeurs et appeler des fonctions indirectement.
- **[code-parse.inc](https://github.com/Y-Less/code-parse.inc/)**
- **[strlib.inc](https://github.com/oscar-broman/strlib/)** - Fonctions string dans SA:MP.
- **[geo-ip.inc](https://github.com/Southclaws/SAMP-geoip/)** - Informations géographiques basées sur l'adresse IP.
- **[samp-aviation](https://github.com/Southclaws/samp-aviation/)** - Pilote automatique dans SA:MP _(en matière d'aviation !)_.
- **[progress2.inc](https://github.com/Southclaws/progress2/)** - Permet de créer des progressbar.
- **[weapon-data.inc](https://github.com/Southclaws/samp-weapon-dat/)** - Permet de régler précisément les weapon data.
- **[MV_Youtube.inc](https://github.com/MichaelBelgium/MV_Youtube)** - Convertisseur de liens youtubes pour les audiostreams.
## Processeurs de commande
- **[izcmd.inc](https://github.com/YashasSamaga/I-ZCMD/)** - Version améliorée de ZCMD
- **[PawnCMD.inc](https://github.com/katursis/Pawn.CMD/)** - Processeur de commande, semble-t-il, le plus rapide.
## Plugins
- **[crashdetect](https://github.com/Zeex/samp-plugin-crashdetect/)** - Outils permettant d'identifier les bugs, erreurs, etc.
- **[JIT](https://github.com/Zeex/samp-plugin-jit/)** - Une fois que votre code est stable, utilisez-le pour le rendre plus rapide.
- **[sscanf](https://github.com/Y-Less/sscanf/)** - Conversez vos strings en multiples values, ints, floats, players, etc.
- **[MySQL](https://github.com/pBlueG/SA-MP-MySQL/)** - MySQL pour votre serveur SA:MP.
- **[streamer](https://github.com/samp-incognito/samp-streamer-plugin/)** - Dépasse certaines limites SA:MP _(pour les objets ou pickups par exemple)_.
- **[nativechecker](https://github.com/openmultiplayer/archive/raw/master/plugins/nativechecker.zip)** - Vérifie les natives au chargement de votre serveur.
- **[Discord Connector](https://github.com/maddinat0r/samp-discord-connector)** - Créez facilement un bot discord lié à votre serveur.
## Plugins de cryptage
- **[whirlpool](https://github.com/Southclaws/samp-whirlpool/)** - Whirlpool pour SA:MP.
- **[bcrypt](https://github.com/LassiR/bcrypt-samp/)** - Bcrypt pour SA:MP.
- **[SHA512](https://github.com/openmultiplayer/archive/raw/master/plugins/SHA512.zip)** - SHA512 pour SA:MP.
## Gamemodes
- **[Example Gamemode](https://github.com/openmultiplayer/example-gamemodes)** - Exemples de gamemodes compatibles avec open.MP.
- **[ScavengeSurvive](https://github.com/Southclaws/ScavengeSurvive)** - gamemode de survie en PvP.
## Tutoriels
- **[Série « Apprendre le PAWN », par C_Far](https://www.youtube.com/watch?v=hJHPcAw93IM&list=PLc9wMs6s5fRSdq-6YXgPkxrB23JiPVVUN)** - série de vidéo permettant d'acquérir rapidement les notions PAWN, et de manière moins didactique qu'un pavé écrit
- **[Série « DEV SAMP », par C_FAR](https://www.youtube.com/watch?v=QycRxxQWzUM&list=PLc9wMs6s5fRQOrWiCeiH6FWWDuyZL04ID)** - plus spécialisé dans le développement de serveurs SAMP, permet d'acquérir rapidement les bases.
| openmultiplayer/web/docs/translations/fr/ressources.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/ressources.md",
"repo_id": "openmultiplayer",
"token_count": 1801
} | 429 |
---
title: OnNPCEnterVehicle
description: Ce rappel est appelé lorsqu'un PNJ entre dans un véhicule.
tags: ["npc"]
---
## Description
Ce rappel est appelé lorsqu'un PNJ entre dans un véhicule.
| Nom | Description |
| ------------ | ------------------------------------------------------- |
| vehicleid | L'ID du véhicule dans lequel le PNJ entre |
| seatid | L'ID de siège que le PNJ utilise |
## Exemples
```c
public OnNPCEnterVehicle(vehicleid, seatid)
{
printf("OnNPCEnterVehicle ID: %d Siège: %d", vehicleid, seatid);
return 1;
}
```
## Rappels Relatives
Les rappels suivants peuvent être utiles, car ils sont liés à ce rappel d'une manière ou d'une autre.
- [OnNPCExitVehicle](OnNPCExitVehicle): Ce rappel est appelé lorsqu'un PNJ quitte un véhicule.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnNPCEnterVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnNPCEnterVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 399
} | 430 |
---
title: OnPlayerDisconnect
description: Cette callback est appelée quand un joueur se déconnecte du serveur.
tags: ["player"]
---
## Paramètres
Cette callback est appelée quand un joueur se déconnecte du serveur.
| Nom | Description |
| -------------- | -------------------------------------------------- |
| `int` playerid | ID du joueur qui se déconnecte |
| `int` reason | Raison de la déconnexion _(v. tableau, infra) |
## Valeur de retour
Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback.
## Exemple
```c
public OnPlayerDisconnect(playerid, reason)
{
new
szString[64],
playerName[MAX_PLAYER_NAME];
GetPlayerName(playerid, playerName, MAX_PLAYER_NAME);
new szDisconnectReason[3][] =
{
"Timeout/Crash",
"(/q)uitter",
"Kick/Ban"
};
format(szString, sizeof szString, "[-] %s a quitté le serveur (%s).", playerName, szDisconnectReason[reason]);
SendClientMessageToAll(0xC4C4C4FF, szString);
return 1;
}
```
## Astuces
:::tip
Certaines fonctions peuvent ne pas fonctionner correctement quand cette callback est utilisée et que le joueur est déjà déconnecté. Cela signifie que vous ne pouvez pas avoir des informations sur celui-ci, par exemple avec GetPlayerIp et GetPlayerPos.
:::
## Callback connexe
- [OnPlayerConnect](OnPlayerConnect) : Quand le joueur se connecte au serveur.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerDisconnect.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerDisconnect.md",
"repo_id": "openmultiplayer",
"token_count": 657
} | 431 |
---
title: OnPlayerLeaveRaceCheckpoint
description: Cette callback est appelée quand un joueur quitte un race checkpoint.
tags: ["player", "checkpoint", "racecheckpoint"]
---
## Paramètres
Cette callback est appelée quand un joueur quitte un race checkpoint.
| Nom | Description |
| -------------- | ------------------------------------------------ |
| `int` playerid | ID du joueur qui a quitté le race checkpoint |
## Valeur de retour
Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback.
## Exemple
```c
public OnPlayerLeaveRaceCheckpoint(playerid)
{
printf("Le joueur %i a quitté le race checkpoint!", playerid);
return 1;
}
```
## Astuces
<TipNPCCallbacks />
## Fonctions connexes
- [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): Créer un checkpoint pour un joueur.
- [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): Désactive le checkpoint actuel du joueur.
- [IsPlayerInCheckpoint](../functions/IsPlayerInRaceCheckpoint): Vérifie si un joueur est un dans race checkpoint.
- [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): Créer un race checkpoint pour un joueur.
- [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): Désactive le race checkpoint actuel du joueur.
- [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): Vérifie si un joueur est dans un race checkpoint.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerLeaveRaceCheckpoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerLeaveRaceCheckpoint.md",
"repo_id": "openmultiplayer",
"token_count": 537
} | 432 |
---
title: OnPlayerText
description: Appelée lorsqu'un joueur envoie un message dans le chat.
tags: ["player"]
---
## Description
Appelée lorsqu'un joueur envoie un message dans le chat.
| Nom | Description |
| --------------- | ---------------------------------------- |
| `int` playerid | L'ID du joueur qui envoie le message |
| `string` text[] | Le texte du message envoyé |
## Valeur de retour
Retourner **0** dans cette callback empêchera l'affichage du message.
## Exemple
```c
public OnPlayerText(playerid, text[])
{
new
textv2[145],
name[MAX_PLAYER_NAME];
GetPlayerName(playerid, name, sizeof (name));
format(textv2, sizeof (textv2), "%d >> %s: %s", playerid, name, text);
SendPlayerMessageToAll(playerid, textv2);
return 0;
//Retourner 0 empêche l'envoi du message par défaut
}
```
## Astuces
<TipNPCCallbacks />
## Fonctions connexes
- [SendPlayerMessageToPlayer](../functions/SendPlayerMessageToPlayer): Force un joueur à envoyer un message à un joueur.
- [SendPlayerMessageToAll](../functions/SendPlayerMessageToAll): Force un joueur à envoyer un message à tous les joueurs.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerText.md",
"repo_id": "openmultiplayer",
"token_count": 486
} | 433 |
---
title: OnVehicleStreamIn
description: Cette callback est appelée lorsqu'un véhicule est chargé (devient visible) pour un joueur.
tags: ["vehicle"]
---
## Paramètres
Cette callback est appelée lorsqu'un véhicule est chargé (devient visible) pour un joueur.
| Nom | Description |
| ----------------- | ----------------------------------------- |
| `int` vehicleid | L'ID du véhicule chargé par le joueur. |
| `int` forplayerid | L'ID du joueur qui a chargé le véhicule. |
## Valeur de retour
Cette callback ne retourne rien, mais doit retourner quelque chose. Autrement dit, `return callback();` ne fonctionnera pas car la callback ne retourne rien, mais un return _(`return 1;` ou `return 0;`)_ doit être effectué dans la callback.
## Exemple
```c
public OnVehicleStreamIn(vehicleid, forplayerid)
{
new string[32];
format(string, sizeof(string), "Vous pouvez désormais voir le véhicule ID: %d.", vehicleid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## Astuces
<TipNPCCallbacks />
## Fonctions connexes
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnVehicleStreamIn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnVehicleStreamIn.md",
"repo_id": "openmultiplayer",
"token_count": 436
} | 434 |
---
title: OnGameModeExit
description: Ez a visszahívás akkor hívódik meg, amikor egy játékmód véget ér, akár a 'gmx' parancs használatával, a szerver leállásakor, vagy akár a GameModeExit-en keresztül.
tags: []
---
## Leírás
Ez a visszahívás akkor hívódik meg, amikor egy játékmód véget ér, akár a 'gmx' parancs használatával, a szerver leállásakor, vagy akár a GameModeExit-en keresztül.
## Példák
```c
public OnGameModeExit()
{
print("Játékmód véget ért.");
return 1;
}
```
## Megjegyzések
:::tip
Ezt a funckiót filterszkriptben arra is lehet használni, hogy érzékelje a ``changemode`` vagy ``gmx``RCON parancsot, mivel a játékmód megváltoztatása nem tölti újra a filterszkriptet.
:::
:::figyelmeztetés
Ha az OnGameModeExit parancsot az 'rcon gmx' konzolparanccsal együtt van használva, ne feledd, hogy előfordulhatnak hibák.
Példa erre a túlzott RemoveBuildingForPlayer hívása az OnGameModeInit alatt, ami az kliens összeomlásához vezethet. Ezt a visszahívást NEM hívja meg, ha a kliens összeomlik, vagy a folyamatot más módon leállítják, például a Linux kill parancsával vagy a Windows konzol bezárás gombjának megnyomásával.
:::
## Kapcsolodó visszhívások
Ezek a visszahívások hasznosak lehetnek mivel valamilyen módon kapcsolódik ehhez a visszahíváshoz.
[OnGameModeInit](OnGameModeInit): Ezt a visszahívást akkor hívja meg amikor egy játékmód elindul.
[OnFilterScriptInit](OnFilterScriptInit): Ezt a visszahívást akkor hívja meg amikor egy filterszkript elindul.
[OnFilterSciptExit](OnFilterScriptExit): Ezt a visszahívást akkor hívja meg amikor egy filterszkript leáll.
## Kapcsolodó funkciók
Ezek a funkciók hasznosak lehetnek mivel valamilyen módon kapcsolódik ehhez a visszahíváshoz.
- [GameModeExit](../functions/GameModeExit): Kilépés a jelenlegi játékmódból.
| openmultiplayer/web/docs/translations/hu/scripting/callbacks/OnGameModeExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/hu/scripting/callbacks/OnGameModeExit.md",
"repo_id": "openmultiplayer",
"token_count": 874
} | 435 |
---
title: OnDialogResponse
description: Callback ini akan terpanggil ketika pemain merespon kepada dialog yang muncul menggunakan ShowPlayerDialog entah itu dengan cara mengklik tombol, menekan ENTER/ESC atau mengklik dua kali list item (jika menggunakan list style dialog).
tags: []
---
## Deskripsi
Callback ini akan terpanggil ketika pemain merespon kepada dialog yang muncul menggunakan ShowPlayerDialog entah itu dengan cara mengklik tombol, menekan ENTER/ESC atau mengklik dua kali list item (jika menggunakan list style dialog).
| Nama | Deskripsi |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | ID dari pemain yang merespon dialog. |
| dialogid | ID dari dialog yang pemain respond sebagaimana ditetapkan di ShowPlayerDialog. |
| response | 1 Untuk tombol kiri dan 0 untuk tombol kanan (Jika hanya satu tombol yang ada, maka hanya 1) |
| listitem | ID dari list item yang dipilih oleh player (dimulai dari 0) (hanya ketika menggunakan list style dialog, sebaliknya akan menjadi -1). |
| inputtext[] | Sebuah text yang dimasukkan kedalam input box dari player atau text dari list item yang terpilih. |
## Returns
Ini akan selalu terpanggil pertama di filterscripts jadi mengembalikan nilai 1 akan melarang filterscript lain untuk melihatnya.
## Contoh
```c
// Define dialog ID agar nantinya kita bisa mengelola responses
#define DIALOG_RULES 1
// Di sebuah perintah
ShowPlayerDialog(playerid, DIALOG_RULES, DIALOG_STYLE_MSGBOX, "Server Rules", "- Gaboleh Curang\n- Gaboleh Spamming\n- Respect sesama admin\n\nApakah anda setuju dengan peraturan diatas?", "Ya", "Tidak");
public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
if(dialogid == DIALOG_RULES)
{
if(response) // Jika mereka mengklik tombol 'Ya' atau menekan enter
{
SendClientMessage(playerid, COLOR_GREEN, "Terimakasih telah menyetujui persyaratannya!");
}
else // Menekan ESC atau mengklik tombol 'Tidak'
{
Kick(playerid);
}
return 1; // Kita berhasil mengelola dialog, jadi return 1. Sama seperti OnPlayerCommandText.
}
return 0; // Anda WAJIB return 0 disini! sama seperti OnPlayerCommandText.
}
#define DIALOG_LOGIN 2
// Di sebuah perintah
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Masukkan passwordnya say:", "Login", "Quit");
public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
if(dialogid == DIALOG_LOGIN)
{
if(!response) // Jika dia mengklik tombol 'Quit' atau menekan ESC
{
Kick(playerid);
}
else // Menekan ENTER atau mengklik tombol 'Login'
{
if(CheckPassword(playerid, inputtext))
{
SendClientMessage(playerid, COLOR_RED, "You are now logged in!");
}
else
{
SendClientMessage(playerid, COLOR_RED, "LOGIN GAGAL.");
// Menampilkan ulang dialog loginnya
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Masukkan passwordnya say:", "Login", "Quit");
}
}
return 1; // Kita berhasil mengelola dialog, jadi return 1. Sama seperti OnPlayerCommandText.
}
return 0; // Anda WAJIB return 0 disini! sama seperti OnPlayerCommandText.
}
#define DIALOG_WEAPONS 3
// In some command
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Weapons", "Desert Eagle\nAK-47\nCombat Shotgun", "Pilih", "Tutup");
public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
if(dialogid == DIALOG_WEAPONS)
{
if(response) // Jika mereka mengklik 'Pilih' atau mengklik dua kali senjata yang dipilih
{
// Berikan mereka senjata yang mereka mau
switch(listitem)
{
case 0: GivePlayerWeapon(playerid, WEAPON_DEAGLE, 14); // Berikan mereka sebuah desert eagle
case 1: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // Berikan mereka sebuah AK-47
case 2: GivePlayerWeapon(playerid, WEAPON_SHOTGSPA, 28); // Berikan mereka sebuah Combat Shotgun
}
}
return 1; // Kita berhasil mengelola dialog, jadi return 1. Sama seperti OnPlayerCommandText.
}
return 0; // Anda WAJIB return 0 disini! sama seperti OnPlayerCommandText.
}
#define DIALOG_WEAPONS 3
// In some command
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Weapons",
"Weapon\tAmmo\tPrice\n\
M4\t120\t500\n\
MP5\t90\t350\n\
AK-47\t120\t400",
"Pilih", "Tutup");
public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
if(dialogid == DIALOG_WEAPONS)
{
if(response) // Jika mereka mengklik 'Pilih' atau mengklik dua kali senjata yang dipilih
{
// Berikan mereka senjata yang mereka mau
case 0: GivePlayerWeapon(playerid, WEAPON_M4, 120); // Berikan mereka sebuah M4
case 1: GivePlayerWeapon(playerid, WEAPON_MP5, 90); // Berikan mereka sebuah MP5
case 2: GivePlayerWeapon(playerid, WEAPON_AK47, 120); // Berikan mereka sebuah AK-47
}
}
return 1; // Kita berhasil mengelola dialog, jadi return 1. Sama seperti OnPlayerCommandText.
}
return 0; // Anda WAJIB return 0 disini! sama seperti OnPlayerCommandText.
}
```
## Notes
:::tip
Parameters dapat memuat nilai yang berbeda berdasarkan style dialog ([klik disini untuk info lebih lanjut](../resources/dialogstyles.md)).
:::
:::tip
Menggunakan switch untuk mensortir dialogid sangatlah dianjurkan, jika anda memiliki banyak dialogid.
:::
:::warning
Dialog pemain tidak akan disembunyikan ketika gamemode dimuat ulang, membuat server untuk mencetak "Warning: PlayerDialogResponse PlayerId: 0 dialog ID doesn't match last send dialog ID" jika pemain merespon kepada dialog tersebut setelah dimuat ulang.
:::
## Fungsi Terkait
- [ShowPlayerDialog](../functions/ShowPlayerDialog.md): Menampilkan dialog kepada pemain.
| openmultiplayer/web/docs/translations/id/scripting/callbacks/OnDialogResponse.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnDialogResponse.md",
"repo_id": "openmultiplayer",
"token_count": 2923
} | 436 |
---
title: OnPlayerEditAttachedObject
description: Callback ini terpanggil ketika player sudah selesai mengedit attached object dengan edit mode.
tags: ["player"]
---
## Deskripsi
Callback ini terpanggil ketika player sudah selesai mengedit attached object dengan edit mode.
| Name | Description |
|------------------------|------------------------------------------------------------------|
| playerid | ID player yang telah selesai mengedit attached object |
| EDIT_RESPONSE:response | 0 jika mereka membatalkan (ESC) atau 1 jika mereka mengklik save |
| index | The index of the attached object (0-9) |
| modelid | Model/object yang diedit oleh player tersebut |
| boneid | 'bone' yang sedang diedit di attached object |
| Float:fOffsetX | Offset X untuk objek yang telah diedit |
| Float:fOffsetY | Offset Y untuk objek yang telah diedit |
| Float:fOffsetZ | Offset Z untuk objek yang telah diedit |
| Float:fRotX | Rotasi X untuk objek yang telah diedit |
| Float:fRotY | Rotasi Y untuk objek yang telah diedit |
| Float:fRotZ | Rotasi Z untuk objek yang telah diedit |
| Float:fScaleX | Skala X untuk objek yang telah diedit |
| Float:fScaleY | Skala Y untuk objek yang telah diedit |
| Float:fScaleZ | Skala Z untuk objek yang telah diedit |
## Returns
1 - Akan mencegah skrip lain untuk memanggil callback ini.
0 - Mengindikasi bahwa callback ini akan terpanggil di script lain.
Selalu terpanggil pertama kali di filterscripts.
## Contoh
```c
enum attached_object_data
{
Float:ao_x,
Float:ao_y,
Float:ao_z,
Float:ao_rx,
Float:ao_ry,
Float:ao_rz,
Float:ao_sx,
Float:ao_sy,
Float:ao_sz
}
new ao[MAX_PLAYERS][MAX_PLAYER_ATTACHED_OBJECTS][attached_object_data];
// Semua data akan tersimpan pada array diatas.
public OnPlayerEditAttachedObject(playerid, EDIT_RESPONSE:response, index, modelid, boneid, Float:fOffsetX, Float:fOffsetY, Float:fOffsetZ, Float:fRotX, Float:fRotY, Float:fRotZ, Float:fScaleX, Float:fScaleY, Float:fScaleZ)
{
if (response)
{
SendClientMessage(playerid, COLOR_GREEN, "Attached object edition saved.");
ao[playerid][index][ao_x] = fOffsetX;
ao[playerid][index][ao_y] = fOffsetY;
ao[playerid][index][ao_z] = fOffsetZ;
ao[playerid][index][ao_rx] = fRotX;
ao[playerid][index][ao_ry] = fRotY;
ao[playerid][index][ao_rz] = fRotZ;
ao[playerid][index][ao_sx] = fScaleX;
ao[playerid][index][ao_sy] = fScaleY;
ao[playerid][index][ao_sz] = fScaleZ;
}
else
{
SendClientMessage(playerid, COLOR_RED, "Attached object edition not saved.");
new i = index;
SetPlayerAttachedObject(playerid, index, modelid, boneid, ao[playerid][i][ao_x], ao[playerid][i][ao_y], ao[playerid][i][ao_z], ao[playerid][i][ao_rx], ao[playerid][i][ao_ry], ao[playerid][i][ao_rz], ao[playerid][i][ao_sx], ao[playerid][i][ao_sy], ao[playerid][i][ao_sz]);
}
return 1;
}
```
## Notes
:::warning
Edit harus dibatalkan jika responsenya 0. Ini harus dilakukan dengan menyimpan offset dll. dalam array SEBELUM menggunakan EditAttachedObject.
:::
## Related Functions
- [EditAttachedObject](../functions/EditAttachedObject): Mengedit object yang sudah diattach.
- [SetPlayerAttachedObject](../functions/SetPlayerAttachedObject): Attach sebuah objek ke player.
| openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerEditAttachedObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerEditAttachedObject.md",
"repo_id": "openmultiplayer",
"token_count": 1864
} | 437 |
---
title: AddCharModel
description: Menambah sebuah custom character model untuk didownload.
tags: []
---
<VersionWarn version='SA-MP 0.3.DL R1' />
## Deskripsi
Menambah sebuah custom character model untuk didownload. Model file biasanya terletak di Player Documents\GTA San Andreas User Files\SAMP\cache didalam folder Server IP dan Port dalam bentuk nama CRC.
| Nama | Deskripsi |
| ------- | -------------------------------------------------------------------------------------------------------------- |
| baseid | Model ID skin dasar yang ingin digunakan (sifat dari karakter & original karakter untuk dipakai setelah download gagal). |
| newid | Model ID skin baru dari jangkauan 20000 sampai 30000 (10000 slot) untuk digunakan nanti bersamaan dengan SetPlayerSkin |
| dffname | Nama file model collision file .dff didalam folder models server secara default (setting artpath). |
| txdname | Nama file model texture file .txd didalam folder models server secara default (setting artpath). |
## Returns
1: Function berhasil dijalankan.
0: Function gagal dijalankan.
## Contoh
```c
public OnGameModeInit()
{
AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd");
AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd");
return 1;
}
```
```c
AddCharModel(305, 20001, "lvpdpc2.dff", "lvpdpc2.txd");
AddCharModel(305, 20002, "lapdpd2.dff", "lapdpd2.txd");
```
## Catatan
:::tip
useartwork harus diaktifkan terlebih dahulu di server settings agar fungsi ini berfungsi.
:::
:::warning
Saat ini tidak ada batasan kapan Anda dapat memanggil fungsi ini, tetapi perhatikan bahwa jika Anda tidak memanggilnya di dalam OnFilterScriptInit/OnGameModeInit, anda bisa membuat player lain beresiko, dimana sudah didalam server, tidak bisa mendownload models.
:::
## Fungsi Terkait
- [SetPlayerSkin](SetPlayerSkin): Mengatur skin player.
| openmultiplayer/web/docs/translations/id/scripting/functions/AddCharModel.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/AddCharModel.md",
"repo_id": "openmultiplayer",
"token_count": 783
} | 438 |
---
title: SetVehicleHealth
description: Set health kendaraan.
tags: ["vehicle"]
---
## Deskripsi
Mengatur Health kendaraan. Ketika kendaraan menurun, mesin kendaraan akan mengeluarkan asap, dan akhirnya api ketika menurun health kendaraan berkurang menjadi 250 (%25)
| Nama | Deskripsi |
| ------------ | ------------------------------------------- |
| vehicleid | ID Kendaraan untuk set health kendaran |
| Float:health | Health, diberikan sebagai nilai Float |
## Returns
1: Fungsi berhasil dijalankan.
0: Fungsi gagal dijalankan. Ini berarti kendaraan tidak ada.
## Contoh
```c
if (strcmp("/fixengine", cmdtext, true) == 0)
{
new
vehicleid = GetPlayerVehicleID(playerid);
SetVehicleHealth(vehicleid, 1000);
SendClientMessage(playerid, COLOUR_WHITE, "Mesin kendaraan berhasil di benarkan");
return 1;
}
```
## Catatan
:::tip
Full health kendaraan adalah 1000. Nilai yang lebih tinggi dimungkinkan. Untuk informasi lebih lanjut tentang health values, lihat [ini.](../resources/vehiclehealth)
:::
## Fungsi terkait
- [GetVehicleHealth](GetVehicleHealth): Cek health kendaraan.
- [RepairVehicle](RepairVehicle): Memperbaiki sebuah kendaraan.
- [SetPlayerHealth](SetPlayerHealth): Mengset health player.
- [OnVehicleDeath](../callbacks/OnVehicleDeath): Dipanggil ketika kendaraan hancur / meledak.
| openmultiplayer/web/docs/translations/id/scripting/functions/SetVehicleHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/SetVehicleHealth.md",
"repo_id": "openmultiplayer",
"token_count": 547
} | 439 |
---
id: bullethittypes
title: Jenis Peluru yang Ditembakkan
---
:::info
ID ini untuk digunakan dengan [OnPlayerWeaponShot](../callbacks/OnPlayerWeaponShot).
:::
---
| Nama | Nilai |
| ----------------------------- | ----- |
| BULLET_HIT_TYPE_NONE | 0 |
| BULLET_HIT_TYPE_PLAYER | 1 |
| BULLET_HIT_TYPE_VEHICLE | 2 |
| BULLET_HIT_TYPE_OBJECT | 3 |
| BULLET_HIT_TYPE_PLAYER_OBJECT | 4 |
---
:::caution
BULLET_HIT_TYPE_PLAYER juga digunakan untuk NPC. Actor diabaikan oleh callback ini dan terdeteksi sebagai BULLET_HIT_TYPE_NONE.
:::
| openmultiplayer/web/docs/translations/id/scripting/resources/bullethittypes.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/resources/bullethittypes.md",
"repo_id": "openmultiplayer",
"token_count": 306
} | 440 |
---
id: tirestates
title: Keadaan Ban
description: Information tentang ukuran byte dan bit status ban yang sesuai.
---
:::note
Keadaan ini untuk digunakan dengan [GetVehicleDamageStatus](../functions/GetVehicleDamageStatus) dan [UpdateVehicleDamageStatus](../functions/UpdateVehicleDamageStatus).
:::
:::note
Kendaraan yang memiliki ban lebih dari 4 (contoh: truk) hanya memiliki 4 keadaan ban.
:::
## Digit ke-sekian menyimpan apa?
Kerusakan semua ban akan disimpan dalam 1 digit (4 bit) untuk kendaraan roda 4 dan 2 bit huntuk kendaraan 2. Setiap bit menyimpan keadaan ban yang di mana **pecah (nilai 1)** dan **tidak pecah (nilai 0)**.
- **bit pertama** menyimpan keadaan ban **kanan-belakang** untuk kendaraan roda 4 atau ban **belakang** untuk kendaraan roda 2.
- **bit ke-dua** menyimpan keadaan ban **kanan-depan** untuk kendaraan roda 4 atau ban **depan** untuk kendaraan roda 2.
- **bit ke-tiga** menyimpan keadaan ban **kiri-belakang** untuk kendaraan roda 4.
- **bit ke-empat** menyimpan keadaan ban **kiri-depan** untuk kendaraan roda 4.
Perhatikan bahwa bit-bit ini dihitung dari belakang, sehingga bit pertama ini bit paling kanan.
## Contoh
Kode berikut menjelaskan bahwa kendaraan roda 4 untuk dua ban pecah dan lainnya tidak:
`0101`
Bagaimanapun, SA-MP mengembalikan nilai desimal, sehingga Anda harus mengubahnya dalam bentuk bilangan biner terlebih dahulu untuk mendapatkan hasil seperti di atas. Seperti contoh di atas, SA-MP akan mengembalikan nilai seperti ini:
`5`
## Info tabel
Berikut adalah representasi visual dari keadaan ban. Kendaraan dilihat dari perspektif atas-bawah, dengan nilai atas sebagai bagian depan kendaraan dan nilai bawah sebagai bagian belakang kendaraan.
**Legenda:**
```
o - inflated tire
x - popped tire
```
### Kendaraan roda 4
4 bit untuk kendaraan 4: (Kr-D)(Kr-B)(Kn-D)(Kn-B) (Kiri-Depan, Kiri-Belakang, Kanan-Depan, dan Kanan-Belakang).
0: (0000)
```c
o-o
| |
o-o
```
1: (0001)
```c
o-o
| |
o-x
```
2: (0010)
```c
o-x
| |
o-o
```
3: (0011)
```c
o-x
| |
o-x
```
4: (0100)
```c
o-o
| |
x-o
```
5: (0101)
```c
o-o
| |
x-x
```
6: (0110)
```c
o-x
| |
x-o
```
7: (0111)
```c
o-x
| |
x-x
```
8: (1000)
```c
x-o
| |
o-o
```
9: (1001)
```c
x-o
| |
o-x
```
10: (1010)
```c
x-x
| |
o-o
```
11: (1011)
```c
x-x
| |
o-x
```
12: (1100)
```c
x-o
| |
x-o
```
13: (1101)
```c
x-o
| |
x-x
```
14: (1110)
```c
x-x
| |
x-o
```
15: (1111)
```c
x-x
| |
x-x
```
Setelah nilai 15 terulang, maka 16 dianggap 0, 17 itu 1, dan seterusnya.
### Kendaraan roda 2 (sepeda, motor)
2 bit untuk kendaraan roda dua: (D)(B) (Depan dan Belakang).
0: (00)
```c
o
|
o
```
1: (01)
```c
o
|
x
```
2: (10)
```c
x
|
o
```
3: (11)
```c
x
|
x
```
Setelah nilai 3 terulang, maka 4 itu 0, 5 itu 1, dan seterusnya.
## Contoh penggunaan
Untuk memecahkan 2 ban dari kendaraan roda 4 tanpa mengubah ban depannya:
```c
new panels, doors, lights, tires;
GetVehicleDamageStatus(vehicleid, panels, doors, lights, tires);
UpdateVehicleDamageStatus(vehicleid, panels, doors, lights, (tires | 0b0101)); // Bagian '0b' artinya adalah nilai panels dibaca dalam bentuk biner. Sama seperti '0x' menandakan bilangan heksadesimal.
```
| openmultiplayer/web/docs/translations/id/scripting/resources/tirestates.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/resources/tirestates.md",
"repo_id": "openmultiplayer",
"token_count": 1704
} | 441 |
---
title: Tutorial
description: Sebuah koleksi tutorial untuk membantu kalian dalam menulis gamemode dan mengatur server kalian.
---
Pada sesi ini, kalian akan menemukan koleksi tutorial untuk membantu kalian dalam menulis gamemode dan mengatur server kalian. Tutorial ini tidak dalam urutan tertentu.
| openmultiplayer/web/docs/translations/id/tutorials/_.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/tutorials/_.md",
"repo_id": "openmultiplayer",
"token_count": 102
} | 442 |
---
title: AddStaticVehicleEx
description: Dodaje „statyczny” pojazd (pojazdy są wstępnie ładowane dla graczy) do gamemodu.
tags: ["vehicle"]
---
## Opis
Dodaje „statyczny” pojazd (pojazdy są wstępnie ładowane dla graczy) do gamemodu. Różnica pomiędzy AddStaticVehicle polega na tym, że ta funkcja umożliwia ustawienie czasu respawnu pojazdu, gdy kierowca go porzuci.
| Nazwa | Opis |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| modelid | ID modelu pojazdu. |
| Float:spawn_X | Koordynat X pojazdu. |
| Float:spawn_Y | Koordynat Y pojazdu. |
| Float:spawn_Z | Koordynat Z pojazdu. |
| Float:z_angle | Kierunek pojazdu (kąt). |
| [color1](../resources/vehiclecolorid.md) | ID pierwszego koloru. -1 to losowy. |
| [color2](../resources/vehiclecolorid.md) | ID drugiego koloru. -1 to losowy. |
| respawn_delay | Czas, po którym pojazd bez kierowcy zostanie zrespawnowany (w sekundach). |
| addsiren | Dodane w 0.3.7; nie będzie działać w starszych wersjach. Domyślna wartość to 0. Umożliwia włączenie syren w każdym pojeździe, który posiada klakson. |
## Zwracane wartości
ID stworzonego pojazdu (pomiędzy 1, a MAX_VEHICLES).
INVALID_VEHICLE_ID (65535) jeżeli pojazd nie został utworzony (osiągnięto limit pojazdów lub podano nieprawidłowe ID modelu).
## Przykłady
```c
public OnGameModeInit()
{
// Dodaje Hydrę (520) do gry, która będzie respawnowana po 15 sekundach od porzucenia
AddStaticVehicleEx (520, 2109.1763, 1503.0453, 32.2887, 82.2873, -1, -1, 15);
return 1;
}
```
## Powiązane funkcje
- [AddStaticVehicle](AddStaticVehicle.md): Dodaje statyczny pojazd.
- [CreateVehicle](CreateVehicle.md): Tworzy pojazd.
| openmultiplayer/web/docs/translations/pl/scripting/functions/AddStaticVehicleEx.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pl/scripting/functions/AddStaticVehicleEx.md",
"repo_id": "openmultiplayer",
"token_count": 2100
} | 443 |
---
title: acos
description: .
tags: []
---
<LowercaseNote />
## Opis
Podaje odwróconą wartość arcus cosinusa w radianach.
| Nazwa | Opis |
| ----------- | ------------- |
| Float:value | Arcus cosinus |
## Zwracane wartości
Główny arcus cosinus z x w przedziale [0, π] radianów. Jeden radian jest równy 180/π stopni.
## Przykłady
```c
//Arcus cosinus dla 0.500000 wynosi 60.000000 stopni.
public OnGameModeInit()
{
new Float:param, Float:result;
param = 0.5;
result = acos(param);
printf("Arcus cosinus dla %f wynosi %f stopni.", param, result);
return 1;
}
```
## Powiązane funkcje
- [floatsin](floatsin.md): Podaje sinus dla określonego kąta.
- [floatcos](floatcos.md): Podaje cosinus dla określonego kąta.
- [floattan](floattan.md): Podaje tangens dla określonego kąta.
| openmultiplayer/web/docs/translations/pl/scripting/functions/acos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pl/scripting/functions/acos.md",
"repo_id": "openmultiplayer",
"token_count": 378
} | 444 |
---
title: OnEnterExitModShop
description: Esta callback é chamada quando o jogador entra ou sai de um modshop.
tags: []
---
## Descrição
Esta callback é chamada quando o jogador entra ou sai de um shop mod.
| Nome | Descrição |
| ---------- | ----------------------------------------------------------------- |
| playerid | O ID do jogador que entrou/saiu do modshop |
| enterexit | 1 se o jogador entrou ou 0 se ele saiu |
| interiorid | O ID do interior do modshop que o jogador entrou (ou 0 caso saia) |
## Retornos
É sempre chamado primeiro nas filterscripts.
## Exemplos
```c
public OnEnterExitModShop(playerid, enterexit, interiorid)
{
if (enterexit == 0) // Se enterexit é 0, isso significa que ele está saindo
{
SendClientMessage(playerid, COLOR_WHITE, "Ótimo carro! Você foi taxado em R$100.");
GivePlayerMoney(playerid, -100);
}
return 1;
}
```
## Notas
:::warning
Bugs Conhecidos: Jogadores colidem quando entram no mesmo modshop.
:::
## Funções Relacionadas
- [AddVehicleComponent](../functions/AddVehicleComponent.md): Adiciona um componente a um veículo.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnEnterExitModShop.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnEnterExitModShop.md",
"repo_id": "openmultiplayer",
"token_count": 524
} | 445 |
---
title: OnPlayerClickPlayerTextDraw
description: Esta callback é chamada quando um jogador clica em uma player-textdraw.
tags: ["player", "textdraw", "playertextdraw"]
---
## Descrição
Esta callback é chamada quando um jogador clica em uma player-textdraw. Não é chamada quando um jogador cancela o modo de seleção (pressionando ESC), entretanto, OnPlayerClickTextDraw é.
| Nome | Descrição |
| ------------ | ----------------------------------------------- |
| playerid | O ID do jogador que selecionou a textdraw |
| playertextid | O ID da playerTextDraw que o jogador selecionou |
## Retorno
1 - Irá previnir que outro filterscript receba esta callback.
0 - Indica que esta callback será passada para o próximo filterscript.
Sempre é chamada primeiro em filterscripts.
## Exemplos
```c
new PlayerText:gPlayerTextDraw[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
// Cria a TextDraw
gPlayerTextDraw[playerid] = CreatePlayerTextDraw(playerid, 10.000000, 141.000000, "MinhaTXD");
PlayerTextDrawTextSize(playerid, gPlayerTextDraw[playerid], 60.000000, 20.000000);
PlayerTextDrawAlignment(playerid, gPlayerTextDraw[playerid],0);
PlayerTextDrawBackgroundColor(playerid, gPlayerTextDraw[playerid],0x000000ff);
PlayerTextDrawFont(playerid, gPlayerTextDraw[playerid], 1);
PlayerTextDrawLetterSize(playerid, gPlayerTextDraw[playerid], 0.250000, 1.000000);
PlayerTextDrawColor(playerid, gPlayerTextDraw[playerid], 0xffffffff);
PlayerTextDrawSetProportional(playerid, gPlayerTextDraw[playerid], 1);
PlayerTextDrawSetShadow(playerid, gPlayerTextDraw[playerid], 1);
// Torna-a selecionável
PlayerTextDrawSetSelectable(playerid, gPlayerTextDraw[playerid], 1);
// Mostra para o jogador
PlayerTextDrawShow(playerid, gPlayerTextDraw[playerid]);
return 1;
}
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (newkeys == KEY_SUBMISSION)
{
SelectTextDraw(playerid, 0xFF4040AA);
}
return 1;
}
public OnPlayerClickPlayerTextDraw(playerid, PlayerText:playertextid)
{
if (playertextid == gPlayerTextDraw[playerid])
{
SendClientMessage(playerid, 0xFFFFFFAA, "Você clicou em uma TextDraw.");
CancelSelectTextDraw(playerid);
return 1;
}
return 0;
}
```
## Notas
:::warning
Quando um jogador pressiona ESC para cancelar o modo de seleção, OnPlayerClickTextDraw será chamada com um ID de TextDraw de: 'INVALID_TEXT_DRAW' (para TextDraw's inválidas). Porém, OnPlayerClickPlayerTextDraw não será chamado neste mesmo caso.
:::
## Funções Relacionadas
- [PlayerTextDrawSetSelectable](../functions/PlayerTextDrawSetSelectable.md): Define se uma TextDraw é selecionável ou não.
- [OnPlayerClickTextDraw](OnPlayerClickTextDraw.md): Chamado quando um jogador clica em uma TextDraw.
- [OnPlayerClickPlayer](OnPlayerClickPlayer.md): Chamado quando um jogador clica em outro.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerClickPlayerTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerClickPlayerTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 1088
} | 446 |
---
title: OnPlayerInteriorChange
description: Chamada quando um jogador muda de interior.
tags: ["player"]
---
## Descrição
Chamada quando um jogador muda de interior. Pode ser chamada pela função SetPlayerInterior ou quando um jogador entre/sai de uma construção.
| Nome | Descrição |
| ------------- | ------------------------------------- |
| playerid | O ID do jogador que mudou de interior |
| newinteriorid | O ID do atual interior do jogador |
| oldinteriorid | O ID do antigo interior do jogador |
## Retorno
É sempre chamado primeiro no gamemode.
## Exemplos
```c
public OnPlayerInteriorChange(playerid, newinteriorid, oldinteriorid)
{
new string[42];
format(string, sizeof(string), "Você foi do interior %d para o interior %d!", oldinteriorid, newinteriorid);
SendClientMessage(playerid, COLOR_ORANGE, string);
return 1;
}
```
## Funções Relacionadas
- [SetPlayerInterior](../functions/SetPlayerInterior.md): Define o interior do jogador.
- [GetPlayerInterior](../functions/GetPlayerInterior.md): Obtém o atual interior do jogador.
- [LinkVehicleToInterior](../functions/LinkVehicleToInterior.md): Muda o interior do qual um veículo é visto.
- [OnPlayerStateChange](OnPlayerStateChange.md): Chamado quando um jogador muda de estado.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerInteriorChange.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerInteriorChange.md",
"repo_id": "openmultiplayer",
"token_count": 477
} | 447 |
---
title: OnPlayerWeaponShot
description: Essa callback é executada todas as vezes que o player realiza um disparo com uma arma.
tags: ["player"]
---
## Descrição
Essa callback é executada todas as vezes que o player realiza um disparo com uma arma. Somente armas com balas são suportadas. Somente o drive-by do passageiro é registrado (drive-by feitos pelo motorista, disparos de helicópteros como o sea sparrow / hunter também não são suportados).
| Nome | Descrição |
|-------------------------|--------------------------------------------------------------------------------------------------------------|
| playerid | ID do jogador que disparou a arma. |
| WEAPON:weaponid | ID da [arma](../resources/weaponids) que foi disparada. |
| BULLET_HIT_TYPE:hittype | O [tipo](../resources/bullethittypes) de onde a bala acertou (Nada, Jogador, Veículo, ou Objeto do jogador). |
| hitid | ID do jogador, veículo ou objeto que a bala acertou. |
| Float:fX | Coordenada X de onde a bala acertou. |
| Float:fY | Coordenada Y de onde a bala acertou. |
| Float:fZ | Coordenada Z de onde a bala acertou. |
## Retornos
0 - Previne a bala de causar danos ao acertar.
1 - Permite a bala causar danos ao acertar.
Sempre executada primeiro em filterscripts, retorne 0 para bloquear que outros filterscripts a vejam.
## Exemplos
```c
public OnPlayerWeaponShot(playerid, WEAPON:weaponid, BULLET_HIT_TYPE:hittype, hitid, Float:fX, Float:fY, Float:fZ)
{
new szString[144];
format(szString, sizeof(szString), "A Arma %i foi disparada. Tipo: %i ID: %i Posição: %f, %f, %f", weaponid, hittype, hitid, fX, fY, fZ);
SendClientMessage(playerid, -1, szString);
return 1;
}
```
## Notas
:::tip
Essa callback é executada somente quando o "lag compensation" está ativado. Caso o tipo de acerto seja:
- `BULLET_HIT_TYPE_NONE`: Os parâmetros fX, fY e fZ irão retornar 0.0 nas coordenadas, caso não haja acerto em nenhuma superficíe (ex. Objeto distante no qual a bala não consegue chegar);
- Outros: Os parâmetros fX, fY e fZ são offsets relativos ao hitid.
:::
:::tip
A função [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors) pode ser usada nessa callback para mais detalhes sobre os vetores da bala.
:::
:::warning
Bug(s) Conhecidos:
- Não é executada quando você atira sendo motorista de um veículo ou caso você esteja olhando para trás com a mira ativa (atirando para o alto). Caso você esteja disparando em um veículo o tipo a ser retornado será `BULLET_HIT_TYPE_VEHICLE` e não `BULLET_HIT_TYPE_PLAYER`, o valor retornado no hitid será o ID do veículo, mesmo que você mire e atire diretamente no jogador que está no veículo o parâmetro `BULLET_HIT_TYPE_VEHICLE` persiste!
- Parcialmente arrumado na versão 0.3.7: Caso 'Fake Weapon Data' seja enviada por um jogador malicioso, outros jogadores podem crashar ou congelar. Para impedir isso de acontecer verifique se o weaponid (arma) pode realmente disparar balas.
:::
## Funções Relacionadas
- [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors): Retorna o vetor do último disparo realizado pelo jogador.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerWeaponShot.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerWeaponShot.md",
"repo_id": "openmultiplayer",
"token_count": 1763
} | 448 |
---
title: AddMenuItem
description: Adiciona um item a um menu especificado.
tags: ["menu"]
---
## Descrição
Esta função adiciona um item a um menu especificado.
| Nome | Descrição |
| ------- | -------------------------------------------- |
| menuid | O ID do menu ao qual o item será adicionado. |
| column | A coluna em que o item será adicionado. |
| title[] | O título do novo item de menu. |
## Retornos
O índice da linha onde este item foi adicionado.
## Exemplos
```c
new Menu:gExampleMenu;
public OnGameModeInit()
{
gExampleMenu = CreateMenu("Seu menu", 2, 200.0, 100.0, 150.0, 150.0);
AddMenuItem(gExampleMenu, 0, "item 1");
AddMenuItem(gExampleMenu, 0, "item 2");
return 1;
}
```
## Notas
:::tip
Gera um crash quando é passado um ID de menu inválido. Cada menu só pode ter até 12 itens (o 13º vai para o lado direito do cabeçalho do nome da coluna (colorido), o 14º e posteriores não são exibidos). É possível usar apenas 2 colunas (0 e 1). Cada item só pode ter até 8 códigos de cor (r, g etc.). O tamanho máximo do título do item de menu é de 31 símbolos.
:::
## Funções Relacionadas
- [CreateMenu](CreateMenu): Cria um menu.
- [SetMenuColumnHeader](SetMenuColumnHeader): Define o cabeçalho de uma das colunas de um menu.
- [DestroyMenu](DestroyMenu): Destrói um menu.
- [OnPlayerSelectedMenuRow](../callbacks/OnPlayerSelectedMenuRow): Chamado quando um jogador seleciona uma linha em um menu.
- [OnPlayerExitedMenu](../callbacks/OnPlayerExitedMenu): Chamado quando um jogador sai de um menu.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AddMenuItem.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AddMenuItem.md",
"repo_id": "openmultiplayer",
"token_count": 631
} | 449 |
---
title: Ban
description: Bane um jogador que está atualmente online no servidor. Ele não poderá mais entrar no servidor. A proibição será baseada em IP e será salva no arquivo samp.ban no diretório raiz do servidor. O BanEx pode ser usado para justificar o banimento. Os banimentos de IP podem ser adicionados ou removidos usando os comandos RCON banip e unbanip (SendRconCommand).
tags: []
---
## Descrição
Bane um jogador que está atualmente online no servidor. Ele não poderá mais entrar no servidor. A proibição será baseada em IP e será salva no arquivo samp.ban no diretório raiz do servidor. O BanEx pode ser usado para justificar o banimento. Os banimentos de IP podem ser adicionados ou removidos usando os comandos RCON banip e unbanip (SendRconCommand).
| Nome | Descrição |
| -------- | ----------------------------- |
| playerid | O ID do jogador a ser banido. |
## Retorno
Esta função não retorna nenhum valor específico.
## Exemplos
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if(strcmp(cmdtext, "/banme", true) == 0)
{
// Bane o jogador que executar este comando.
Ban(playerid);
return 1;
}
}
// Para exibir uma mensagem (por exemplo, motivo) para o jogador antes que a conexão seja fechada
// você tem que usar um cronômetro (timer) para criar um atraso. Esse atraso precisa ser de apenas alguns milissegundos,
// mas este exemplo usa um segundo inteiro apenas por garantia.
forward DelayedBan(playerid);
public DelayedBan(playerid)
{
Ban(playerid);
}
public OnPlayerCommandText(playerid, cmdtext[])
{
if(strcmp(cmdtext, "/banme", true) == 0)
{
// Bane o jogador que executar este comando.
// Primeiro, manda a ele uma mensagem.
SendClientMessage(playerid, 0xFF0000FF, "Você foi banido!");
// Bane-os um segundo depois da execução do comando por um cronômetro (timer).
SetTimerEx("DelayedBan", 1000, false, "d", playerid);
return 1;
}
return 0;
}
```
## Notas
:::warning
Qualquer ação realizada diretamente antes do Ban() (como enviar uma mensagem com SendClientMessage) não chegará ao jogador. Um cronômetro (timer) deve ser usado para atrasar o banimento.
:::
## Funções Relacionadas
- [BanEx](../functions/BanEx.md): Bane um jogador com uma razão específica.
- [Kick](../functions/Kick.md): Expulsa um jogador do servidor.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/Ban.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/Ban.md",
"repo_id": "openmultiplayer",
"token_count": 956
} | 450 |
---
title: GangZoneHideForPlayer
description: Esconde a gangzone para um jogador.
tags: ["player", "gangzone"]
---
## Descrição
Esconde a gangzone para um jogador.
| Nome | Descrição |
| -------- | ------------------------------------------------ |
| playerid | O ID do jogador para o qual esconder a gangzone. |
| zone | O ID da gangzone a esconder. |
## Retorno
Esta função não retorna nenhum valor específico.
## Exemplos
```c
new gGangZoneId;
public OnGameModeInit()
{
gGangZoneId = GangZoneCreate(1248.011, 2072.804, 1439.348, 2204.319);
return 1;
}
public OnPlayerSpawn(playerid)
{
GangZoneShowForPlayer(playerid, gGangZoneId, 0xFF0000FF);
return 1;
}
public OnPlayerDeath(playerid, killerid, WEAPON:reason)
{
GangZoneHideForPlayer(playerid, gGangZoneId);
return 1;
}
```
## Funções Relacionadas
- [GangZoneCreate](GangZoneCreate): Cria uma gangzone.
- [GangZoneDestroy](GangZoneDestroy): Destrói uma gangzone.
- [GangZoneShowForPlayer](GangZoneShowForPlayer): Mostra uma gangzone a um jogador.
- [GangZoneShowForAll](GangZoneShowForAll): Mostra uma gangzone para todos os jogadores.
- [GangZoneHideForAll](GangZoneHideForAll): Esconde uma gangzone para todos os jogadores.
- [GangZoneFlashForPlayer](GangZoneFlashForPlayer): Faz uma gangzone piscar para um jogador.
- [GangZoneFlashForAll](GangZoneFlashForAll): Faz uma gangzone piscar para todos os jogadores.
- [GangZoneStopFlashForPlayer](GangZoneStopFlashForPlayer): Pare uma Gangzone de piscar para um jogador.
- [GangZoneStopFlashForAll](GangZoneStopFlashForAll): Pare uma Gangzone de piscar para todos os jogadores.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GangZoneHideForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GangZoneHideForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 651
} | 451 |
---
title: GetPlayerName
description: Obtém o nome de um jogador.
tags: ["player"]
---
## Descrição
Obtém o nome de um jogador.
| Nome | Descrição |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | O ID do jogador do qual deseja obter o nome. |
| name[] | A array para armazenar o nome, passado por referência. |
| len | O comprimento da string que deve ser armazenada. Recomendado que seja MAX_PLAYER_NAME + 1. O + 1 é necessário parar levar em conta o caractere nulo (null terminator). |
## Retorno
O nome do jogador é armazenado na array especificada.
## Exemplos
```c
public OnPlayerConnect(playerid)
{
// Obtém o nome do jogador que se conectou e exibe uma mensagem de entrada para outros jogadores.
new name[MAX_PLAYER_NAME + 1];
GetPlayerName(playerid, name, sizeof(name));
new string[MAX_PLAYER_NAME + 23 + 1];
format(string, sizeof(string), "%s entrou no servidor.", name);
SendClientMessageToAll(0xC4C4C4FF, string);
return 1;
}
```
## Notas
:::tip
O nome do jogador pode ter até 24 caracteres (a partir da 0.3d R2) usando SetPlayerName. Isso é definido na a_samp.inc em MAX_PLAYER_NAME. Porém, no client só pode entrar com um nickname entre 3 e 20 caracteres, caso contrário a conexão será rejeitada e o jogador terá que sair e escolher um nome válido.
:::
## Funções Relacionadas
- [SetPlayerName](SetPlayerName.md): Define o nome de um jogador.
- [GetPlayerIp](GetPlayerIp.md): Obtém o IP de um jogador.
- [GetPlayerPing](GetPlayerPing.md): Obtém o ping de um jogador.
- [GetPlayerScore](GetPlayerScore.md): Obtém a pontuação/nível de um jogador.
- [GetPlayerVersion](GetPlayerVersion.md): Obtém a versão-client de um jogador.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetPlayerName.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetPlayerName.md",
"repo_id": "openmultiplayer",
"token_count": 1050
} | 452 |
---
title: acos
description: Obter o valor invertido de um cosseno em graus.
tags: ["math"]
---
<LowercaseNote />
## Descrição
Obter o valor invertido de um cosseno em graus. Na trigonometria, o arco cosseno é a operação inversa do cosseno.
| Nome | Descrição |
| ----------- | ------------------------------------------------------------ |
| Float:value | valor cujo arco cosseno é calculado, no intervalo [-1,+1]. |
## Retorno
O ângulo em graus, no intervalo [0.0,180.0].
## Exemplos
```c
//O arco cosseno de 0,500000 é de 60,000000 graus.
public OnGameModeInit()
{
new Float:param, Float:result;
param = 0.5;
result = acos(param);
printf("O arco cosseno de %f é %f graus.", param, result);
return 1;
}
```
## Funções Relacionadas
- [floatsin](floatsin): Obter o seno de um ângulo específico.
- [floatcos](floatcos): Obter o cosseno de um ângulo específico.
- [floattan](floattan): Obter a tangente de um ângulo específico.
- [asin](asin): Obter o valor invertido de um seno em graus.
- [atan](atan): Obter o valor invertido de uma tangente em graus.
- [atan2](atan2): Obter o valor invertido múltiplo de uma tangente em graus.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/acos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/acos.md",
"repo_id": "openmultiplayer",
"token_count": 514
} | 453 |
---
title: OnEnterExitModShop
description: Acest callback este apelat atunci când un jucâtor intră sau iese dintr-un mod shop.
tags: []
---
## Descriere
Acest callback este apelat când un jucâtor intră sau iese dintr-un mod shop.
| Nume | Descriere |
| ---------- | --------------------------------------------------------------------- |
| playerid | ID-ul jucătorului care a intrat sau a ieșit din modshop |
| enterexit | 1 dacă jucătorul a intrat sau 0 dacă a ieșit |
| interiorid | ID-ul interiorului modshop-ului dacă playerul intră (sau 0 dacă iese) |
## Returnări
Mereu este apelat primul în filterscript-uri.
## Exemple
```c
public OnEnterExitModShop(playerid, enterexit, interiorid)
{
if (enterexit == 0) // Dacă enterexit e 0, atunci înseamnă că jucătorul iese
{
SendClientMessage(playerid, COLOR_WHITE, "Frumoasă tigaie! Ai fost taxat cu $100.");
GivePlayerMoney(playerid, -100);
}
return 1;
}
```
## Note
:::warning
Bug-uri cunoscute: Jucătorii se lovesc înte ei când intră în același mod shop.
:::
## Funcții asociate
- [AddVehicleComponent](../functions/AddVehicleComponent.md): Adaugă o componentă unei mașini.
| openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnEnterExitModShop.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnEnterExitModShop.md",
"repo_id": "openmultiplayer",
"token_count": 600
} | 454 |
---
title: OnPlayerEditObject
description: Acest callback este apelat atunci când un jucător termină editarea unui obiect (EditObject/EditPlayerObject).
tags: ["player"]
---
## Descriere
Acest callback este apelat atunci când un jucător termină editarea unui obiect (EditObject/EditPlayerObject).
| Nume | Descriere |
|------------------------|----------------------------------------------------------------|
| playerid | ID-ul jucătorului care a editat un obiect |
| playerobject | 0 dacă este un obiect global sau 1 dacă este un obiect player. |
| objectid | ID-ul obiectului editat |
| EDIT_RESPONSE:response | [type of response](../resources/objecteditionresponsetypes) |
| Float:fX | Decalajul X pentru obiectul care a fost editat |
| Float:fY | Decalajul Y pentru obiectul care a fost editat |
| Float:fZ | Decalajul Z pentru obiectul care a fost editat |
| Float:fRotX | Rotația X pentru obiectul care a fost editat |
| Float:fRotY | Rotația Y pentru obiectul care a fost editat |
| Float:fRotZ | Rotația Z pentru obiectul care a fost editat |
## Returnări
1 - Va împiedica alte scripturi să primească acest callback.
0 - Indică faptul că acest callback va fi transmis următorului script.
Este întotdeauna numit primul în filterscript-uri.
## Exemple
```c
public OnPlayerEditObject(playerid, playerobject, objectid, EDIT_RESPONSE:response, Float:fX, Float:fY, Float:fZ, Float:fRotX, Float:fRotY, Float:fRotZ)
{
new
Float: oldX,
Float: oldY,
Float: oldZ,
Float: oldRotX,
Float: oldRotY,
Float: oldRotZ;
GetObjectPos(objectid, oldX, oldY, oldZ);
GetObjectRot(objectid, oldRotX, oldRotY, oldRotZ);
if (!playerobject) // Dacă acesta este un obiect global, sincronizați poziția pentru alți jucători
{
if (!IsValidObject(objectid))
{
return 1;
}
SetObjectPos(objectid, fX, fY, fZ);
SetObjectRot(objectid, fRotX, fRotY, fRotZ);
}
switch (response)
{
case EDIT_RESPONSE_FINAL:
{
// Jucătorul a făcut clic pe pictograma de salvare
// Faceți orice aici pentru a salva poziția actualizată a obiectului (și rotația)
}
case EDIT_RESPONSE_CANCEL:
{
//Jucătorul a anulat, așa că puneți obiectul înapoi în vechea poziție
if (!playerobject) //Obiectul nu este un obiect player
{
SetObjectPos(objectid, oldX, oldY, oldZ);
SetObjectRot(objectid, oldRotX, oldRotY, oldRotZ);
}
else
{
SetPlayerObjectPos(playerid, objectid, oldX, oldY, oldZ);
SetPlayerObjectRot(playerid, objectid, oldRotX, oldRotY, oldRotZ);
}
}
}
return 1;
}
```
## Note
:::warning
Când utilizați „EDIT_RESPONSE_UPDATE”, rețineți că acest callback nu va fi apelat la eliberarea unei editări în curs, ceea ce duce la desincronizarea ultimei actualizări a „EDIT_RESPONSE_UPDATE” cu poziția curentă a obiectelor.
:::
## Related Functions
- [EditObject](../functions/EditObject): Editați un obiect.
- [CreateObject](../functions/CreateObject): Creați un obiect.
- [DestroyObject](../functions/DestroyObject): Distruge un obiect.
- [MoveObject](../functions/MoveObject): Mutați un obiect. | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerEditObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerEditObject.md",
"repo_id": "openmultiplayer",
"token_count": 1851
} | 455 |
---
title: OnPlayerRequestDownload
description: Acest callback este apelat atunci când un jucător solicită descărcarea unui model personalizat.
tags: ["player"]
---
<VersionWarn name='callback' version='SA-MP 0.3.DL R1' />
## Descriere
Acest callback este apelat atunci când un jucător solicită descărcarea unui model personalizat.
| Nume | Descriere |
| -------- | ------------------------------------------------------------------- |
| playerid | ID-ul jucătorului care solicită descărcarea modelului personalizat. |
| type | Tipul cererii (vezi mai jos). |
| crc | Suma de control CRC a fișierului model personalizat. |
## Returnări
0 - Respinge solicitarea de descărcare
1 - Acceptați cererea de descărcare
## Exemple
```c
#define DOWNLOAD_REQUEST_EMPTY (0)
#define DOWNLOAD_REQUEST_MODEL_FILE (1)
#define DOWNLOAD_REQUEST_TEXTURE_FILE (2)
new baseurl[] = "https://files.sa-mp.com/server";
public OnPlayerRequestDownload(playerid, type, crc)
{
new fullurl[256+1];
new dlfilename[64+1];
new foundfilename=0;
if (!IsPlayerConnected(playerid)) return 0;
if (type == DOWNLOAD_REQUEST_TEXTURE_FILE) {
foundfilename = FindTextureFileNameFromCRC(crc,dlfilename,64);
}
else if (type == DOWNLOAD_REQUEST_MODEL_FILE) {
foundfilename = FindModelFileNameFromCRC(crc,dlfilename,64);
}
if (foundfilename) {
format(fullurl,256,"%s/%s",baseurl,dlfilename);
RedirectDownload(playerid,fullurl);
}
return 0;
}
```
## Funcții similare
- [OnPlayerFinishedDownloading](OnPlayerFinishedDownloading): Apelat când un jucător termină descărcarea modelelor personalizate. | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerRequestDownload.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerRequestDownload.md",
"repo_id": "openmultiplayer",
"token_count": 762
} | 456 |
---
title: OnUnoccupiedVehicleUpdate
description: Acest callback este apelat atunci când clientul unui jucător actualizează/sincronizează poziția unui vehicul pe care nu îl conduce.
tags: ["vehicle"]
---
## Descriere
Acest callback este apelat atunci când clientul unui jucător actualizează/sincronizează poziția unui vehicul pe care nu îl conduce. Acest lucru se poate întâmpla în afara vehiculului sau când jucătorul este pasagerul unui vehicul care nu are șofer.
| Name | Descriere |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vehicleid | ID-ul jucătorului care a trimis o actualizare de sincronizare a poziției vehiculului. |
| playerid | ID-ul jucătorului care a trimis o sincronizare a poziției vehiculului |
| passenger_seat | ID-ul scaunului dacă jucătorul este pasager. 0=nu în vehicul, 1=pasager din față, 2=spate stânga 3=spate dreapta 4+ este pentru autocar/autobuz etc. cu multe locuri pentru pasageri. |
| new_x | Noua coordonată X a vehiculului. Acest parametru a fost adăugat în 0,3z. Lasă-l afară dacă folosești o versiune anterioară. |
| new_y | Noua coordonată Y a vehiculului. Acest parametru a fost adăugat în 0,3z. Lasă-l afară dacă folosești o versiune anterioară. |
| new_z | Noua coordonată Z a vehiculului. Acest parametru a fost adăugat în 0,3z. Lasă-l afară dacă folosești o versiune anterioară. |
| vel_x | Noua viteză X a vehiculului. Acest parametru a fost adăugat în 0,3z R4. Lasă-l afară dacă folosești o versiune anterioară. |
| vel_y | Noua viteză X a vehiculului. Acest parametru a fost adăugat în 0,3z R4. Lasă-l afară dacă folosești o versiune anterioară. |
| vel_z | Noua viteză X a vehiculului. Acest parametru a fost adăugat în 0,3z R4. Lasă-l afară dacă folosești o versiune anterioară. |
## Returnări
Este întotdeauna numit primul în filterscript-uri, așa că returnarea 0 acolo blochează și alte scripturi să-l vadă.
## Exemple
```c
public OnUnoccupiedVehicleUpdate(vehicleid, playerid, passenger_seat, Float:new_x, Float:new_y, Float:new_z, Float:vel_x, Float:vel_y, Float:vel_z)
{
// Verificați dacă s-a mutat departe
if (GetVehicleDistanceFromPoint(vehicleid, new_x, new_y, new_z) > 50.0)
{
// Respinge actualizarea
return 0;
}
return 1;
}
```
## Note
:::warning
Acest apel invers este apelat foarte frecvent pe secundă per vehicul neocupat. Ar trebui să vă abțineți de la implementarea unor calcule intensive sau operațiuni intensive de scriere/citire a fișierelor în acest apel invers. GetVehiclePos va returna coordonatele vechi ale vehiculului înainte de această actualizare.
:::
## Funcții similare | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnUnoccupiedVehicleUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnUnoccupiedVehicleUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 1881
} | 457 |
---
title: AddStaticPickup
description: Această funcție adaugă o preluare „statică” la joc.
tags: []
---
## Descriere
Această funcție adaugă o preluare „statică” la joc. Aceste pickup-uri acceptă arme, sănătate, armuri etc., cu capacitatea de a funcționa fără a le scripta (armele / sănătatea / armura vor fi date automat).
| Nume | Descriere |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [model](../resources/pickupids.md) | Modelul pick-up-ului. |
| [type](../resources/pickuptypes.md) | Tipul de preluare. Determină modul în care răspunde pickup-ul atunci când este ridicat. |
| Float:X | Coordonata X pentru a crea preluarea la. |
| Float:Y | Coordonata Y pentru a crea preluarea la. |
| Float:Z | Coordonata Z pentru a crea preluarea la. |
| virtualworld | ID-ul lumii virtuale pentru a pune acest pickup. Folosiți -1 pentru a afișa pickup-ul în toate lumile. |
## Se intoarce
1 dacă pickup-ul este creat cu succes.
0 dacă nu s-a putut crea.
## Exemple
```c
public OnGameModeInit()
{
// Create a pickup for armor
AddStaticPickup(1242, 2, 1503.3359, 1432.3585, 10.1191, 0);
// Create a pickup for some health, right next to the armour
AddStaticPickup(1240, 2, 1506.3359, 1432.3585, 10.1191, 0);
return 1;
}
```
## Note
:::tip
Această funcție nu returnează un ID de preluare pe care îl puteți utiliza, de exemplu, OnPlayerPickUpPickup. Utilizați CreatePickup dacă doriți să atribuiți ID-uri.
:::
## Funcții conexe
- [CreatePickup](CreatePickup.md): Creați un pick-up.
- [DestroyPickup](DestroyPickup.md): Distruge un pick-up.
- [OnPlayerPickUpPickup](../callbacks/OnPlayerPickUpPickup.md): Apelat când un jucător ridică un pickup.
| openmultiplayer/web/docs/translations/ro/scripting/functions/AddStaticPickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/functions/AddStaticPickup.md",
"repo_id": "openmultiplayer",
"token_count": 1220
} | 458 |
---
title: "ID-urile oaselor"
---
:::note
Se foloseste in [SetPlayerAttachedObject](../functions/SetPlayerAttachedObject).
:::
| ID | Bone |
| --- | ------------------------ |
| 1 | Coloana vertebrală |
| 2 | Cap |
| 3 | Brațul stâng |
| 4 | Bratul drept |
| 5 | Mâna stângă |
| 6 | Mâna dreapta |
| 7 | Coapsa stângă |
| 8 | Coapsa dreapta |
| 9 | Piciorul stang |
| 10 | Piciorul drept |
| 11 | Gamba dreapta |
| 12 | Gamba stângă |
| 13 | Antebratul stang |
| 14 | Antebrațul drept |
| 15 | Clavicula stângă (umăr) |
| 16 | Clavicula dreaptă (umăr) |
| 17 | Gat |
| 18 | Fălcile |
| openmultiplayer/web/docs/translations/ro/scripting/resources/boneid.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/resources/boneid.md",
"repo_id": "openmultiplayer",
"token_count": 521
} | 459 |
---
title: Внесение вклада
description: Как внести вклад в Wiki SA-MP и документацию open.mp.
---
Этот источник документации открыт для внесений любых изменений. Всё, что вам нужно, это аккаунт [GitHub](https://github.com) и свободное время. Вам даже не нужно знать Git, вы можете всё сделать через веб интерфейс!
Если вы хотите помочь с поддержкой определённого языка, откройте документ [`CODEOWNERS`](https://github.com/openmultiplayer/web/blob/master/CODEOWNERS) и добавьте по примеру строку с директорией с переводами вместе с вашим именем пользователя.
## Редактирование контента
На каждой странице есть кнопка, которая переносит вас на страницу с редактированием:
![Кнопка редактирования находится на каждой странице](/images/contributing/edit-this-page.png)
Например, клик по [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) перенесёт вас на [эту страницу](https://github.com/openmultiplayer/web/edit/master/docs/scripting/functions/SetVehicleAngularVelocity.md), которая встретит вас с текстовым редактором для редактирования содержимого (если вы уже вошли в аккаунт GitHub, конечно же).
Сделайте ваши правки и подтвердите "Pull Request" (запрос на слияние), это означает, что руководитель Wiki и другие члены сообщества смогут увидеть ваши изменения, обсудить, что требуется добавить и/или исправить и уже после внести изменения в основной репозиторий.
## Добавление нового контента
Добавление нового контента немного сложнее. Вы можете сделать это двумя способами:
### Сайт GitHub
Когда вы просматриваете директорию на сайте GitHub, вы можете заметить кнопку "Добавить файл" в правом верхнем углу списка файлов:
![Кнопка добавить файл](/images/contributing/add-new-file.png)
Вы можете либо загрузить уже написанный файл Markdown, либо записать его непосредственно в текстовом редакторе GitHub.
Файл _обязан_ иметь расширение `.md` и содержать в себе разметку на языке Markdown. Для большей информации о Markdown, прочтите [данную статью](https://guides.github.com/features/mastering-markdown/).
Как только всё сделано, нажмите "Предложить новый файл" и будет открыт новый запрос на слияние (Pull request).
### Git
Если вы хотите использовать Git, всё, что вам необходимо - это клонировать репозиторий с Wiki:
```sh
git clone https://github.com/openmultiplayer/wiki.git
```
Откройте это в вашем любимом текстовом редакторе. Я рекомендую Visual Studio Code, поскольку он имеет некоторые полезные средства для форматирования файлов Markdown. Как можно увидеть, я пишу это, используя Visual Studio Code!
![Visual Studio Code](/images/contributing/vscode.png)
Я рекомендую 2 расширения, которые упростят ваше работу:
- [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) от David Anson - это расширение, которое гарантирует, что ваш Markdown отформатирован правильно. Это предотвращает некоторые синтаксические и семантические ошибки. Не все предупреждения важны, но некоторые могут помочь улучшить читаемость. Используйте лучшее решение, а если вы сомневаетесь, просто спросите проверяющего!
- [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) от Prettier.js Team - это форматер, который автоматически отформатирует ваши файлы Markdown, чтобы все они использовали согласованный стиль. Репозиторий Wiki имеет некоторые настройки в своем "package.json", которые расширение должно автоматически использовать. Обязательно включите "формат при сохранении" в настройках редактора, чтобы ваши файлы Markdown автоматически форматировались при каждом сохранении!
## Замечания, Подсказки и Соглашения
### Внутренние ссылки
Не используйте абсолютные пути на внутренние ссылки сайта. Используйте относительные пути.
- ❌
```md
Используется с [OnPlayerClickPlayer](https://www.open.mp/docs/scripting/callbacks/OnPlayerClickPlayer)
```
- ✔
```md
Используется с [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer)
```
`../` означает "подняться на директорию выше", так что если вы редактируете файл в папке `functions` и ссылаетесь на папку `callbacks`, вам следует использовать `../` чтобы вернуться в папку `scripting/`, а затем `callbacks/` чтобы перейти в папку `calbacks`, а затем имя файла (без `.md`), на который вы хотите сослаться.
### Изображения
Изображения помещаются в папку `/static/images`. Затем, когда вы хотите использовать изображение через `![]()`, вам просто следует использовать `/images/`, как базовый путь (не нужно указывать `static` это просто для репозитория).
Если вы сомневаетесь, прочтите другую страницу, на которой используются изображения, и скопируйте, как сделано там.
### Метаданные
Первой вещью в _любом_ документе должны быть метаданные:
```mdx
---
title: Мой документация
description: Эта страница о различных штуках, вещах и бургерах, воу!
---
```
Каждая страница должна содержать заголовок и описание.
Для полного списка контента, который может содержаться между `---`, прочтите [документацию Docusaurus](https://v2.docusaurus.io/docs/markdown-features#markdown-headers).
### Заголовки
Не создавайте заголовки первого уровня (`<h1>`) с использованием `#`, поскольку они создаются автоматически. Ваши заголовки _всегда_ должны быть `##`
- ❌
```md
# Мой заголовок
Это документация для ...
# Подзаголовок
```
- ✔
```md
Эта документация для ...
## Подзаголовок
```
### Используйте сниппет `Code`, для технической документации
Когда вы пишете текст, содержащий имена функций, цифры, выражения или что-либо ещё, не относящееся к стандартной письменной речи, выделяйте их с помощью \`апострофов\`, как здесь. Это позволяет упростить отделение обычной письменной речи от технической документации - имен функций и фрагментов кода.
- ❌
> Функция fopen возвращает значение с тегом File:, не будет проблем на этой строке, если переменная, в которую записывается значение, тоже имеет тег File: (обратите внимание, что регистр символов должен быть одинаковым). Однако, в следующей строке значение 4 добавляется к дескриптору файла. 4 не имеет тега [...]
- ✔
> Функция `fopen` возвращает значение с тегом `File:`, не будет проблем на этой строке, если переменная, в которую записывается значение, тоже имеет тег `File:` (обратите внимание, что регистр символов должен быть одинаковым). Однако, в следующей строке значение 4 добавляется к дескриптору файла. `4` не имеет тега [...]
В примере выше, `fopen` это имя функции, не английское слово, поэтому следует его ограничить сниппетом `code`, чтобы помочь выделить его на фоне остального контента.
Так же, если текст отсылается на блок демонстративного кода, это поможет читателю соотнести описание и остальной текст с самим примером в виде кода.
### Таблицы
Если у таблицы есть заголовок, он помещается в верхнюю часть:
- ❌
```md
| | |
| ------- | ------------------------------------ |
| Здоровье| Статус двигателя |
| 650 | Не повреждён |
| 650-550 | Белый дым |
| 550-390 | Серый дым |
| 390-250 | Чёрный дым |
| < 250 | Горит (взорвётся очень скоро) |
```
- ✔
```md
| Здоровье| Статус двигателя |
| ------- | ------------------------------------ |
| 650 | Не повреждён |
| 650-550 | Белый дым |
| 550-390 | Серый дым |
| 390-250 | Чёрный дым |
| < 250 | Горит (взорвётся очень скоро) |
```
## Миграция из SA-MP Wiki
Множество контента было перемещено, но если вы заметили, что какая-либо страница отсутствует, то вот краткий гайд по преобразованию контента в формат Markdown.
### Получение HTML кода
1. Нажмите на кнопку
(Firefox)
![image](/images/contributing/04f024579f8d.png)
(Chrome)
![image](/images/contributing/f62bb8112543.png)
2. Наведите курсор на крайний левый угол главной страницы Wiki, пока не выделится тег `#content`
![image](/images/contributing/65761ffbc429.png)
Или найдите `<div id=content>`
![image](/images/contributing/77befe2749fd.png)
3. Скопируйте внутренний HTML код
![image](/images/contributing/8c7c75cfabad.png)
Сейчас у вас есть _только_ HTML код оригинального _содержимого_ страницы, то, что нас волнует, и вы можете преобразовать это в Markdown.
### Преобразование из HTML в Markdown
Для преобразования обычного HTML (без таблиц) в Markdown используйте:
https://domchristie.github.io/turndown/
![image](/images/contributing/77f4ea555bbb.png)
^^ Заметьте, что таблица теперь испорчена окончательно...
### Таблицы HTML в таблицы Markdown
Поскольку верхний инструмент не поддерживает работу с таблицами, используйте данный вариант:
https://jmalarcon.github.io/markdowntables/
И скопируйте только элемент `<table>`:
![image](/images/contributing/57f171ae0da7.png)
### Очистка
Преобразование, скорее всего, не будет совершенным. Так что вам придется сделать небольшую ручную очистку. Перечисленные выше расширения форматирования должны помочь в этом, но вам все равно придется потратить некоторое время на ручную работу.
Если у вас нет времени, не волнуйтесь! Отправьте незаконченный черновик, и кто-то другой сможет продолжить с того места, где вы остановились!
## Лицензионное соглашение
Все проекты open.mp имеют [Лицензионное Соглашение Участника](https://cla-assistant.io/openmultiplayer/homepage). В общем, это означает, что вы соглашаетесь позволить нам использовать вашу работу и поместить ее под лицензию с открытым исходным кодом. Когда вы впервые откроете Pull-запрос, бот CLA-Assistant разместит ссылку, по которой вы сможете подписать соглашение.
| openmultiplayer/web/docs/translations/ru/meta/Contributing.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ru/meta/Contributing.md",
"repo_id": "openmultiplayer",
"token_count": 8686
} | 460 |
---
title: "Управление сервером"
descripion: Полезные команды для управления сервером.
---
## Изменения игрового режима
### Запуска стороннего/загруженного из интернета режима
- Откройте папку с файлами сервера
- Скопируйте загруженные файлы с расширением .amx в папку gamemodes
- Используйте RCON команду для переключения на новый режим (2.1)
- Как альтернативу, вы можете использовать этот мод, как дополнительный для переключения (2.3)
### Использование подгружаемых скриптов/фильтрскриптов (Filterscripts)
Шаги точно такие же, как и с модом, но если отличия:
- Поместите файл с расширением .amx в папку `filterscripts`
- Добавьте скрипт в server.cfg: `filterscripts <названиескрипта>`
## Установка пароля
- Если вы хотите установить на сервер пароль, чтобы войти могли только доверенные люди, добавьте следующую строку в [server.cfg](server.cfg):
```
password парольдлявхода
```
- Это сделает ваш сервер защищённым с помощью пароль, где 'парольдлявхода' будет паролем, необходимым, для входа на сервер, всё логично. Вы можете изменить пароль на любой, какой вздумается.
- Пароль так же можно изменить через RCON прямо во время работы сервера с помощью команды `/rcon password парольдлявхода` или `password парольдлявхода`, используя консоль сервера или удалённую консоль.
- Убрать вход по паролю можно, установив `0` в качестве пароля любым из вышеуказанных способов.
## Использование RCON
### Авторизация
Вы можете авторизоваться, как RCON администратор, при помощи команды `/rcon login password` в игре, или используя [удалённую консоль (rcon)](RemoteConsole).
Пароль будет точно таким же, как и тот, что указан в [server.cfg](server.cfg)
### Блокировка пользователей
##### samp.ban
samp.ban это файл, располагающейся в папку с сервером и содержащий в себе список блокировок, он содержит следующую информацию:
- IP
- Дата блокировки
- Время блокировки
- Имя игрока (Имя игрока или причина блокировки, см. [BanEx](../../functions/BanEx))
- Тип блокировки
Чтобы заблокировать пользователя, добавьте строку по примеру:
```
IP_ПОЛЬЗОВАТЕЛЯ [28/05/09 | 13:37:00] НИК - ПРИЧИНА БЛОКИРОВКИ
```
Где `IP_ПОЛЬЗОВАТЕЛЯ` это IP адрес, который вы хотите заблокировать.
##### Функция Ban()
Функция [Ban](../../functions/Ban) используется для аналогичного метода блокировки, но из самого скрипта. Функция [BanEx](../../functions/BanEx) добавляет к параметрам причину блокировки:
```
13.37.13.37 [28/05/09 | 13:37:00] Читер - INGAME BAN
```
##### Блокировка через RCON
Чтобы заблокировать пользователя, используя полномочия RCON администратора, необходимо использовать команду `ban` (Как блокировать по IP, смотрите далее).
Пример использования:
```
# В игре:
/rcon ban ID_ИГРОКА
# Консоль:
ban ID_ИГРОКА
```
##### banip
Чтобы заблокировать определённый IP адрес, используя полномочия RCON администратора, необходимо использовать команду `banip`.
Пример использования:
```
# В игре:
/rcon banip IP
# Консоль:
banip IP
```
### Разблокировка
Есть 2 способа разблокировать заблокированного пользователя.
- Удалить соответствующую строку из samp.ban
- Использовать RCON команду `unbanip`
#### samp.ban
samp.ban это файл, располагающейся в папку с сервером и содержащий в себе список блокировок, он содержит следующую информацию:
- IP
- Дата блокировки
- Время блокировки
- Имя игрока (Имя игрока или причина блокировки, см. [BanEx](../../functions/BanEx))
- Тип блокировки
Например:
```
127.8.57.32 [13/06/09 | 69:69:69] NONE - IP BAN
13.37.13.37 [28/05/09 | 13:37:00] Kalcor - INGAME BAN
```
Чтобы разблокировать данных пользователей, удалите нужные строки из файла и используйте RCON команду `reloadbans`, чтобы обновить список блокировок, не перезапуская сервер.
#### unbanip
RCON команда `unbanip` используется для разблокировки IP адреса (`/rcon unbanip IP_АДРЕС` в игре или `unbanip IP_АДРЕС` в консоли).
Пример:
```
13.37.13.37 [28/05/09 | 13:37:00] Kalcon - INGAME BAN
```
```
# В игре:
/rcon unbanip 13.37.13.37
# Консоль
unbanip 13.37.13.37
```
Не забудьте использовать RCON команду `reloadbans`, чтобы обновить список блокировок, не перезапуская сервер.
#### reloadbans
Как было указано ранее, файл `samp.ban` содержит в себе список блокировок. Содержимое этого файла считывается лишь при запуске сервера, однако, если вы хотите обновить список во время работы сервера, используйте RCON команду `reloadbans`
### RCON команды
Введите `cmdlist`, чтобы получить список со всеми доступными RCON командами:
| Команда | Описание |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `/rcon cmdlist` | Выводит список команд. |
| `/rcon varlist` | Выводит список текущих параметров в [server.cfg](server.cfg) |
| `/rcon exit` | Прекращает работу сервера. |
| `/rcon echo [text]` | Выводит текст, указанный в `[text]` в консоль сервера. |
| `/rcon hostname [name]` | Изменяет название сервера в поиске (_пример: /rcon hostname my server_). |
| `/rcon gamemodetext [name]` | Изменяет название режима сервера в поиске (_пример: /rcon gamemodetext my gamemode_). |
| `/rcon mapname [name]` | Изменяет название карты сервера в поиске (_пример: /rcon mapname San Andreas_). |
| `/rcon exec [filename]` | Выполняет файл, содержащий настройки, как в server.cfg (_пример: /rcon exec blah.cfg_). |
| `/rcon kick [ID]` | Кикает игрока с указанным ID (_пример: /rcon kick 2_). |
| `/rcon ban [ID]` | Блокирует ID (_пример: /rcon ban 2_). |
| `/rcon changemode [mode]` | Изменяет загруженный игровой мод (_пример: /rcon changemode new_v2_). |
| `/rcon gmx` | Загрузит следующий игровой мод, указанный в `gamemodes` в [server.cfg](server.cfg). |
| `/rcon reloadbans` | Обновляет список блокировок из файла samp.ban. |
| `/rcon reloadlog` | Перезагружает файл server_log.txt. Нет видимого эффекта. |
| `/rcon say` | Отправить сообщение в чат на сервере из RCON (_пример: `/rcon say привет всем` выведет всем в чат `Admin: привет всем`). |
| `/rcon players` | Выводит список игроков на сервере (с их именами, IP и пингом). |
| `/rcon banip [IP]` | Блокирует указанный IP (_пример: /rcon banip 127.0.0.1_). |
| `/rcon unbanip [IP]` | Разблокирует указанный IP (_пример: /rcon unbanip 127.0.0.1_). |
| `/rcon gravity` | Меняет гравитацию на сервере (_пример: /rcon gravity 0.008_). |
| `/rcon weather [ID]` | Меняет погоду на сервере (_пример: /rcon weather 1_). |
| `/rcon loadfs` | Загружает указанный filterscript (_пример: /rcon loadfs adminfs_). |
| `/rcon weburl [server url]` | Изменяет веб-адрес сервера в лаунчере |
| `/rcon unloadfs` | Выгружает указанный filterscript (_пример: /rcon unloadfs adminfs_). |
| `/rcon reloadfs` | Перезагружает указанный filterscript (_пример: /rcon reloadfs adminfs_). |
| `/rcon rcon\_password [PASSWORD]` | Меняет пароль RCON администраторов |
| `/rcon password [password]` | Устанавливает/снимает пароль сервера |
| `/rcon messageslimit [count]` | Устанавливает лимит сообщений, отправляемых клиентом в секунду. (по умолчанию 500) |
| `/rcon ackslimit [count]` | Устанавливает лимит подтверждений (acks), отправляемых клиентом в секунду (по умолчанию 3000) |
| `/rcon messageholelimit [count]` | Устанавливает лимит 'messagehole', отправляемых клиентом в секунду (по умолчанию 3000) |
| `/rcon playertimeout [limit m/s]` | Устанавливает количество миллисекунд, после которых игрок будет отключен, если не отправляет никаких пакетов. (по умолчанию 1000) |
| `/rcon language [language]` | Изменяет текст языка сервера в лаунчере (_пример: /rcon language Русский_). |
Первые 4 вышеприведённых команды для 0.3z R2 были сделаны для противодействия атакам на серверы SA-MP, вызывающие фризы и сбои. Поэтому, используйте их на своём сервере. Значения по умолчанию должны быть корректными для большинства серверов, однако, если вы замечаете ложные кики из-за этого, просто повысьте значения, пока невинные игроки не были исключены/заблокированы. [Подробнее здесь](http://web-old.archive.org/web/20190426141744/https://forum.sa-mp.com/showpost.php?p=2990193&postcount=47).
### Коллбэки и функции
Следующие коллбэки и функции могут быть полезными, так как относятся к содержимому данной статьи.
#### Коллбэки
- [OnRconLoginAttempt](../../callbacks/OnRconLoginAttempt): Вызывается, когда совершается попытка авторизации RCON администратора.
#### Функции
- [IsPlayerAdmin](../../functions/IsPlayerAdmin): Проверяет, авторизован-ли пользователь, как RCON администратор.
- [SendRconCommand](../../functions/SendRconCommand): Отправляет любую из вышеприведённых RCON команд прямо из скрипта.
| openmultiplayer/web/docs/translations/ru/server/ControllingServer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ru/server/ControllingServer.md",
"repo_id": "openmultiplayer",
"token_count": 9492
} | 461 |
---
title: OnGameModeInit
description: Ta callback se aktivira, ko se zažene "gamemode".
tags: []
---
## Opis
Ta callback se aktivira, ko se zažene "gamemode".
## Primeri
```c
public OnGameModeInit()
{
print(""Gamemode" začela!");
return 1;
}
```
## Opombe
:::tip
To funkcijo lahko uporabljate tudi znotraj "filterscript" da zazna, če "gamemode" spremenite z uporabo ukazov RCON, kot je "changemode" ali "gmx", ker sprememba "gamemode" se ne zažene znova "filterscript".
:::
## Povezane Funkcijo
| openmultiplayer/web/docs/translations/sl/scripting/callbacks/OnGameModeInit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/sl/scripting/callbacks/OnGameModeInit.md",
"repo_id": "openmultiplayer",
"token_count": 229
} | 462 |
---
title: CreateExplosionForPlayer
description: Kreira eksploziju koja je vidljiva samo jednom igracu.
tags: ["player"]
---
## Opis
Kreira eksploziju koja je vidljiva samo jednom igracu. Funkcija moze da se koristi kako bi se eksplozija odvojila od ostalih igraca ili prikazala u posebnom virtuelnom svetu.
| Ime | Opis |
| ------------ | ----------------------------------- |
| playerid | ID igraca kome kreiramo eksploziju. |
| Float:X | X koordinata eksplozije |
| Float:Y | Y koordinata eksplozije |
| Float:Z | Z koordinata eksplozije |
| type | Tip eksplozije. |
| Float:Radius | Velicina eksplozije. |
## Uzvracanja
Ova funkcija uvek vraca 1, iako je funkcija neuspesno izvrsena (igrac ne postoji, nepravilna velicina, ili nepostojuci tip eksplozije).
## Primeri
```c
if (strcmp(cmdtext, "/burnme", true) == 0)
{
new Float: playerPos[3];
GetPlayerPos(playerid, playerPos[0], playerPos[1], playerPos[2]);
CreateExplosionForPlayer(playerid, playerPos[0], playerPos[1], playerPos[2], 1, 10.0);
return 1;
}
```
## Beleske
:::tip
Postoji limit koji ogranicava koliko igrac moze videti eksplozija odjednom. To je 10.
:::
## Srodne Funkcije
- [CreateExplosion](CreateExplosion.md): Kreira eksploziju koja je vidljiva svim igracima.
| openmultiplayer/web/docs/translations/sr/scripting/functions/CreateExplosionForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/sr/scripting/functions/CreateExplosionForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 671
} | 463 |
---
title: OnFilterScriptExit
description: Callback นี้ถูกเรียกเมื่อฟิลเตอร์สคริปต์ยกเลิกการโหลด
tags: []
---
## คำอธิบาย
Callback นี้ถูกเรียกเมื่อฟิลเตอร์สคริปต์ยกเลิกการโหลด
| ชื่อ | คำอธิบาย |
| ---- | -------- |
## ตัวอย่าง
```c
public OnFilterScriptExit()
{
print("\n--------------------------------------");
print(" ยกลิกการโหลด Filterscript ของฉันแล้ว");
print("--------------------------------------\n");
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnFilterScriptExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnFilterScriptExit.md",
"repo_id": "openmultiplayer",
"token_count": 436
} | 464 |
---
title: OnPlayerEnterCheckpoint
description: This callback is called when a player enters the checkpoint set for that player.
tags: ["player", "checkpoint"]
---
## คำอธิบาย
This callback is called when a player enters the checkpoint set for that player.
| Name | Description |
| -------- | -------------------------------------- |
| playerid | The player who entered the checkpoint. |
## ส่งคืน
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
//In this example, a checkpoint is created for the player when spawning,
//which creates a vehicle and disables the checkpoint.
public OnPlayerSpawn(playerid)
{
SetPlayerCheckpoint(playerid, 1982.6150, -220.6680, -0.2432, 3.0);
return 1;
}
public OnPlayerEnterCheckpoint(playerid)
{
CreateVehicle(520, 1982.6150, -221.0145, -0.2432, 82.2873, -1, -1, 60000);
DisablePlayerCheckpoint(playerid);
return 1;
}
```
## บันทึก
:::tip
NPC สามารถเรียก Callback นี้ได้
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetPlayerCheckpoint](../../scripting/functions/SetPlayerCheckpoint.md): Create a checkpoint for a player.
- [DisablePlayerCheckpoint](../../scripting/functions/DisablePlayerCheckpoint.md): Disable the player's current checkpoint.
- [IsPlayerInCheckpoint](../../scripting/functions/IsPlayerInRaceCheckpoint.md): Check if a player is in a checkpoint.
- [SetPlayerRaceCheckpoint](../../scripting/functions/SetPlayerRaceCheckpoint.md): Create a race checkpoint for a player.
- [DisablePlayerRaceCheckpoint](../../scripting/functions/DisablePlayerRaceCheckpoint.md): Disable the player's current race checkpoint.
- [IsPlayerInRaceCheckpoint](../../scripting/functions/IsPlayerInRaceCheckpoint.md): Check if a player is in a race checkpoint.
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerEnterCheckpoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerEnterCheckpoint.md",
"repo_id": "openmultiplayer",
"token_count": 730
} | 465 |
---
title: OnPlayerRequestSpawn
description: Called when a player attempts to spawn via class selection either by pressing SHIFT or clicking the 'Spawn' button.
tags: ["player"]
---
## คำอธิบาย
Called when a player attempts to spawn via class selection either by pressing SHIFT or clicking the 'Spawn' button.
| Name | Description |
| -------- | --------------------------------------------- |
| playerid | The ID of the player that requested to spawn. |
## ส่งคืน
It is always called first in filterscripts so returning 0 there also blocks other scripts from seeing it.
## ตัวอย่าง
```c
public OnPlayerRequestSpawn(playerid)
{
if (!IsPlayerAdmin(playerid))
{
SendClientMessage(playerid, -1, "You may not spawn.");
return 0;
}
return 1;
}
```
## บันทึก
:::tip
NPC สามารถเรียก Callback นี้ได้
:::
:::tip
To prevent players from spawning with certain classes, the last viewed class must be saved in a variable in OnPlayerRequestClass.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerRequestSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerRequestSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 461
} | 466 |
---
title: OnVehicleDamageStatusUpdate
description: This callback is called when a vehicle element such as doors, tires, panels, or lights change their damage status.
tags: ["vehicle"]
---
## คำอธิบาย
This callback is called when a vehicle element such as doors, tires, panels, or lights change their damage status.
| Name | Description |
| --------- | ------------------------------------------------------------------------------------------------------ |
| vehicleid | The ID of the vehicle that was changed its damage status. |
| playerid | The ID of the player who synced the change in the damage status (who had the car damaged or repaired). |
## ส่งคืน
1 - Will prevent other filterscripts from receiving this callback.
0 - Indicates that this callback will be passed to the next filterscript.
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
public OnVehicleDamageStatusUpdate(vehicleid, playerid)
{
// Get the damage status of all the components
new panels, doors, lights, tires;
GetVehicleDamageStatus(vehicleid, panels, doors, lights, tires);
// Set the tires to 0, which means none are popped
tires = 0;
// Update the vehicle's damage status with unpopped tires
UpdateVehicleDamageStatus(vehicleid, panels, doors, lights, tires);
return 1;
}
```
## บันทึก
:::tip
This does not include vehicle health changes
:::
:::tip
For some useful functions for working with vehicle damage values, see here.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetVehicleDamageStatus](../../scripting/functions/GetVehicleDamageStatus.md): Get the vehicle damage state for each part individually.
- [UpdateVehicleDamageStatus](../../scripting/functions/UpdateVehicleDamageStatus.md): Update the vehicle damage.
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleDamageStatusUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleDamageStatusUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 762
} | 467 |
---
title: AddStaticVehicle
description: Adds a 'static' vehicle (models are pre-loaded for players) to the gamemode.
tags: ["vehicle"]
---
## คำอธิบาย
Adds a 'static' vehicle (models are pre-loaded for players) to the gamemode.
| Name | Description |
| ----------------------------------------------------- | -------------------------------------- |
| modelid | The Model ID for the vehicle. |
| Float:spawn_X | The X-coordinate for the vehicle. |
| Float:spawn_Y | The Y-coordinate for the vehicle. |
| Float:spawn_Z | The Z-coordinate for the vehicle. |
| Float:z_angle | Direction of vehicle - angle. |
| [color1](../../scripting/resources/vehiclecolorid.md) | The primary color ID. -1 for random. |
| [color2](../../scripting/resources/vehiclecolorid.md) | The secondary color ID. -1 for random. |
## ส่งคืน
The vehicle ID of the vehicle created (between 1 and MAX_VEHICLES).
INVALID_VEHICLE_ID (65535) if vehicle was not created (vehicle limit reached or invalid vehicle model ID passed).
## ตัวอย่าง
```c
public OnGameModeInit()
{
// Add a Hydra to the game
AddStaticVehicle(520, 2109.1763, 1503.0453, 32.2887, 82.2873, 0, 1);
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [AddStaticVehicleEx](../../scripting/functions/AddStaticVehicleEx.md): Add a static vehicle with custom respawn time.
- [CreateVehicle](../../scripting/functions/CreateVehicle.md): Create a vehicle.
- [DestroyVehicle](../../scripting/functions/DestroyVehicle.md): Destroy a vehicle.
| openmultiplayer/web/docs/translations/th/scripting/functions/AddStaticVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/AddStaticVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 865
} | 468 |
---
title: AttachPlayerObjectToVehicle
description: Attach a player object to a vehicle.
tags: ["player", "vehicle"]
---
## คำอธิบาย
Attach a player object to a vehicle.
| Name | Description |
| ------------- | ------------------------------------------------ |
| playerid | The ID of the player the object was created for. |
| objectid | The ID of the object to attach to the vehicle. |
| vehicleid | The ID of the vehicle to attach the object to. |
| Float:OffsetX | The X position offset for attachment. |
| Float:OffsetY | The Y position offset for attachment. |
| Float:OffsetZ | The Z position offset for attachment. |
| Float:RotX | The X rotation offset for attachment. |
| Float:RotY | The Y rotation offset for attachment. |
| Float:RotZ | The Z rotation offset for attachment. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerStateChange(playerid, PLAYER_STATE:newstate, PLAYER_STATE:oldstate)
{
if (newstate == PLAYER_STATE_DRIVER) // If player enters vehicle
{
// Attach massive cow.
new cow_object = CreatePlayerObject(playerid, 16442, 0, 0, 0, 0, 0, 0);
AttachPlayerObjectToVehicle(playerid, cow_object, GetPlayerVehicleID(playerid), 0.0, 0.0, 1.0, 0.0, 0.0, 0.0);
}
}
```
## บันทึก
:::tip
You need to create the object before attempting to attach it to a vehicle.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreatePlayerObject](../../scripting/functions/CreateObject.md): Create an object for only one player.
- [DestroyPlayerObject](../../scripting/functions/DestroyObject.md): Destroy a player object.
- [IsValidPlayerObject](../../scripting/functions/IsValidObject.md): Checks if a certain player object is vaild.
- [MovePlayerObject](../../scripting/functions/MoveObject.md): Move a player object.
- [StopPlayerObject](../../scripting/functions/StopObject.md): Stop a player object from moving.
- [SetPlayerObjectRot](../../scripting/functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../../scripting/functions/GetPlayerObjectPos.md): Locate a player object.
- [SetPlayerObjectPos](../../scripting/functions/SetPlayerObjectPos.md): Set the position of a player object.
- [GetPlayerObjectRot](../../scripting/functions/GetPlayerObjectRot.md): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](../../scripting/functions/AttachPlayerObjectToPlayer.md): Attach a player object to a player
- [CreateObject](../../scripting/functions/CreateObject.md): Create an object.
- [DestroyObject](../../scripting/functions/DestroyObject.md): Destroy an object.
- [IsValidObject](../../scripting/functions/IsValidObject.md): Checks if a certain object is vaild.
- [MoveObject](../../scripting/functions/MoveObject.md): Move a object.
- [StopObject](../../scripting/functions/StopObject.md): Stop an object from moving.
- [SetObjectPos](../../scripting/functions/SetObjectPos.md): Set the position of an object.
- [SetObjectRot](../../scripting/functions/SetObjectRot.md): Set the rotation of an object.
- [GetObjectPos](../../scripting/functions/GetObjectPos.md): Locate an object.
- [GetObjectRot](../../scripting/functions/GetObjectRot.md): Check the rotation of an object.
- [AttachObjectToPlayer](../../scripting/functions/AttachObjectToPlayer.md): Attach an object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/AttachPlayerObjectToVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/AttachPlayerObjectToVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 1237
} | 469 |
---
title: CreateExplosion
description: Create an explosion at the specified coordinates.
tags: []
---
## คำอธิบาย
Create an explosion at the specified coordinates.
| Name | Description |
| ------------ | -------------------------------------------------------- |
| Float:X | The X coordinate of the explosion. |
| Float:Y | The Y coordinate of the explosion. |
| Float:Z | The Z coordinate of the explosion. |
| type | The [type](../resources/explosionlist) of the explosion. |
| Float:radius | The radius of the explosion. |
## ส่งคืน
This function always returns 1, even when the explosion type and/or radius values are invalid.
## ตัวอย่าง
```c
public OnPlayerEnterCheckpoint(playerid)
{
// Get the player's position
new Float:x, Float:y, Float:z;
GetPlayerPos(playerid, x, y, z);
// Create an explosion at the player's position
CreateExplosion(x, y, z, 12, 10.0);
return 1;
}
```
## บันทึก
:::tip
There is a limit as to how many explosions can be seen at once by a player. This is roughly 10.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateExplosionForPlayer](CreateExplosionForPlayer.md): Create an explosion which is visible for only a single player.
- [Explosion Types](../resources/explosionlist): A list of all the explosion types.
| openmultiplayer/web/docs/translations/th/scripting/functions/CreateExplosion.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/CreateExplosion.md",
"repo_id": "openmultiplayer",
"token_count": 635
} | 470 |
---
title: DestroyPickup
description: Destroys a pickup created with CreatePickup.
tags: []
---
## คำอธิบาย
Destroys a pickup created with CreatePickup.
| Name | Description |
| ------ | ----------------------------------------------------------- |
| pickup | The ID of the pickup to destroy (returned by CreatePickup). |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
// Create a pickup for armor.
pickup_armour = CreatePickup ( 1242, 2, 1503.3359, 1432.3585, 10.1191 );
//some time later...
DestroyPickup(pickup_armour);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreatePickup](../../scripting/functions/CreatePickup.md): Create a pickup.
- [OnPlayerPickUpPickup](../../scripting/callbacks/OnPlayerPickUpPickup.md): Called when a player picks up a pickup.
| openmultiplayer/web/docs/translations/th/scripting/functions/DestroyPickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/DestroyPickup.md",
"repo_id": "openmultiplayer",
"token_count": 376
} | 471 |
---
title: EnableStuntBonusForPlayer
description: Toggle stunt bonuses for a player.
tags: ["player"]
---
## คำอธิบาย
Toggle stunt bonuses for a player. Enabled by default.
| Name | Description |
| -------- | ------------------------------------------------- |
| playerid | The ID of the player to toggle stunt bonuses for. |
| enable | 1 to enable stunt bonuses and 0 to disable them. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The player is not connected.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid)
{
EnableStuntBonusForPlayer(playerid, 0); // Disable stunt bonuses when the player connects to the server.
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [EnableStuntBonusForAll](../functions/EnableStuntBonusForAll): Toggle stunt bonuses for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/EnableStuntBonusForPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/EnableStuntBonusForPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 348
} | 472 |
---
title: GangZoneShowForAll
description: Shows a gangzone with the desired color to all players.
tags: ["gangzone"]
---
## คำอธิบาย
Shows a gangzone with the desired color to all players.
| Name | Description |
| ----- | --------------------------------------------------------------------------------------------------------- |
| zone | The ID of the gangzone to show (returned by GangZoneCreate). |
| color | The color to show the gang zone, as an integer or hex in RGBA color format. Alpha transparency supported. |
## ส่งคืน
1: The function executed successfully. The gang zone was shown for all players.
0: The function failed to execute. The gangzone does not exist.
## ตัวอย่าง
```c
new gGangzone;
public OnGameModeInit()
{
gGangzone = GangZoneCreate(1248.011, 2072.804, 1439.348, 2204.319);
return 1;
}
public OnPlayerSpawn(playerid)
{
if (IsPlayerAdmin(playerid))
{
GangZoneShowForAll(gGangzone, COLOR_RED);
}
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GangZoneCreate](../functions/GangZoneCreate): Create a gangzone.
- [GangZoneDestroy](../functions/GangZoneDestroy): Destroy a gangzone.
- [GangZoneShowForPlayer](../functions/GangZoneShowForPlayer): Show a gangzone for a player.
- [GangZoneHideForPlayer](../functions/GangZoneHideForPlayer): Hide a gangzone for a player.
- [GangZoneHideForAll](../functions/GangZoneHideForAll): Hide a gangzone for all players.
- [GangZoneFlashForPlayer](../functions/GangZoneFlashForPlayer): Make a gangzone flash for a player.
- [GangZoneFlashForAll](../functions/GangZoneFlashForAll): Make a gangzone flash for all players.
- [GangZoneStopFlashForPlayer](../functions/GangZoneStopFlashForPlayer): Stop a gangzone flashing for a player.
- [GangZoneStopFlashForAll](../functions/GangZoneStopFlashForAll): Stop a gangzone flashing for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/GangZoneShowForAll.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GangZoneShowForAll.md",
"repo_id": "openmultiplayer",
"token_count": 790
} | 473 |
---
title: GetNetworkStats
description: Gets the server's network stats and stores them in a string.
tags: []
---
## คำอธิบาย
Gets the server's network stats and stores them in a string.
| Name | Description |
| ----------- | -------------------------------------------------------------- |
| retstr[] | The string to store the network stats in, passed by reference. |
| retstr_size | The length of the string to be stored. |
## ส่งคืน
This function always returns 1.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext, "/netstats"))
{
new stats[400+1];
GetNetworkStats(stats, sizeof(stats)); // get the servers networkstats
ShowPlayerDialog(playerid, 0, DIALOG_STYLE_MSGBOX, "Server Network Stats", stats, "Close", "");
}
return 1;
}
```
```
Server Ticks: 200
Messages in Send buffer: 0
Messages sent: 142
Bytes sent: 8203
Acks sent: 11
Acks in send buffer: 0
Messages waiting for ack: 0
Messages resent: 0
Bytes resent: 0
Packetloss: 0.0%
Messages received: 54
Bytes received: 2204
Acks received: 0
Duplicate acks received: 0
Inst. KBits per second: 28.8
KBits per second sent: 10.0
KBits per second received: 2.7
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerNetworkStats](../functions/GetPlayerNetworkStats): Gets a player networkstats and saves it into a string.
- [NetStats_GetConnectedTime](../functions/NetStats_GetConnectedTime): Get the time that a player has been connected for.
- [NetStats_MessagesReceived](../functions/NetStats_MessagesReceived): Get the number of network messages the server has received from the player.
- [NetStats_BytesReceived](../functions/NetStats_BytesReceived): Get the amount of information (in bytes) that the server has received from the player.
- [NetStats_MessagesSent](../functions/NetStats_MessagesSent): Get the number of network messages the server has sent to the player.
- [NetStats_BytesSent](../functions/NetStats_BytesSent): Get the amount of information (in bytes) that the server has sent to the player.
- [NetStats_MessagesRecvPerSecond](../functions/NetStats_MessagesRecvPerSecond): Get the number of network messages the server has received from the player in the last second.
- [NetStats_PacketLossPercent](../functions/NetStats_PacketLossPercent): Get a player's packet loss percent.
- [NetStats_ConnectionStatus](../functions/NetStats_ConnectionStatus): Get a player's connection status.
- [NetStats_GetIpPort](../functions/NetStats_GetIpPort): Get a player's IP and port.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetNetworkStats.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetNetworkStats.md",
"repo_id": "openmultiplayer",
"token_count": 922
} | 474 |
---
title: GetPlayerCameraMode
description: Returns the current GTA camera mode for the requested player.
tags: ["player"]
---
## คำอธิบาย
Returns the current GTA camera mode for the requested player. The camera modes are useful in determining whether a player is aiming, doing a passenger driveby etc.
| Name | Description |
| -------- | -------------------------------------------------- |
| playerid | The ID of the player whose camera mode to retrieve |
## ส่งคืน
The camera mode as an integer (or -1 if player is not connected)
## ตัวอย่าง
```c
/* when the player types 'cameramode' in to the chat box, they'll see this. */
public OnPlayerText(playerid, text[])
{
if (strcmp(text, "cameramode", true) == 0)
{
new szMessage[22];
format(szMessage, sizeof(szMessage), "Your camera mode: %d", GetPlayerCameraMode(playerid));
SendClientMessage(playerid, 0xA9C4E4FF, szMessage);
}
return 0;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerCameraPos](../functions/GetPlayerCameraPos): Find out where the player's camera is.
- [GetPlayerCameraFrontVector](../functions/GetPlayerCameraFrontVector): Get the player's camera front vector
- [SetPlayerCameraPos](../functions/SetPlayerCameraPos): Set a player's camera position.
- [SetPlayerCameraLookAt](../functions/SetPlayerCameraLookAt): Set where a player's camera should face.
- [SetCameraBehindPlayer](../functions/SetCameraBehindPlayer): Set a player's camera behind them.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraMode.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraMode.md",
"repo_id": "openmultiplayer",
"token_count": 563
} | 475 |
---
title: GetPlayerIp
description: Get the specified player's IP address and store it in a string.
tags: ["player", "ip address"]
---
## คำอธิบาย
Get the specified player's IP address and store it in a string.
| Name | Description |
| -------- | -------------------------------------------------------------------- |
| playerid | The ID of the player to get the IP address of. |
| ip[] | The string to store the player's IP address in, passed by reference. |
| len | The maximum length of the IP address (recommended 16). |
## ส่งคืน
The player's IP address is stored in the specified array.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid)
{
new plrIP[16];
GetPlayerIp(playerid, plrIP, sizeof(plrIP));
if (!strcmp(plrIP, "127.0.0.1"))
{
SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to your server, master :)");
}
return 1;
}
```
## บันทึก
:::tip
PAWN is case-sensitive. GetPlayerIP will not work.
:::
:::warning
**SA-MP server**: This function **does not work** when used in [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect) because the player is already disconnected. It will return an invalid IP (255.255.255.255).
Save players' IPs under [OnPlayerConnect](../callbacks/OnPlayerConnect) if they need to be used under [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect).
**open.mp server**: This function **work** when used in [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [NetStats_GetIpPort](../functions/NetStats_GetIpPort): Get a player's IP and port.
- [GetPlayerName](../functions/GetPlayerName): Get a player's name.
- [GetPlayerPing](../functions/GetPlayerPing): Get the ping of a player.
- [GetPlayerVersion](../functions/GetPlayerVerion): Get a player's client-version.
- [OnIncomingConnection](../callbacks/OnIncomingConnection): Called when a player is attempting to connect to the server.
- [OnPlayerConnect](../callbacks/OnPlayerConnect): Called when a player connects to the server.
- [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect): Called when a player leaves the server.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerIp.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerIp.md",
"repo_id": "openmultiplayer",
"token_count": 836
} | 476 |
---
title: GetPlayerSpecialAction
description: Retrieves a player's current special action.
tags: ["player"]
---
## คำอธิบาย
Retrieves a player's current special action.
| Name | Description |
| -------- | -------------------------------------------------- |
| playerid | The ID of the player to get the special action of. |
## ส่งคืน
The special action of the player (see: [Special Actions](../../scripting/resources/specialactions.md)).
## ตัวอย่าง
```c
public OnPlayerUpdate(playerid)
{
// Ban players if they have a jetpack
if (GetPlayerSpecialAction(playerid) == SPECIAL_ACTION_USEJETPACK)
{
Ban(playerid);
}
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerSpecialAction: Set a player's special action.
- GetPlayerState: Get a player's current state.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerSpecialAction.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerSpecialAction.md",
"repo_id": "openmultiplayer",
"token_count": 372
} | 477 |
---
title: GetPlayerWeaponState
description: Check the state of a player's weapon.
tags: ["player"]
---
## คำอธิบาย
Check the state of a player's weapon.
| Name | Description |
| -------- | --------------------------------------------------- |
| playerid | The ID of the player to obtain the weapon state of. |
## ส่งคืน
The state of the player's weapon. 0 if player specified does not exist.
## ตัวอย่าง
```c
public OnPlayerSpawn(playerid)
{
SetPVarInt(playerid, "WepState", GetPlayerWeaponState(playerid));
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GivePlayerWeapon: Give a player a weapon.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerWeaponState.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerWeaponState.md",
"repo_id": "openmultiplayer",
"token_count": 311
} | 478 |
---
title: GetVehicleHealth
description: Get the health of a vehicle.
tags: ["vehicle"]
---
## คำอธิบาย
Get the health of a vehicle.
| Name | Description |
| ------------- | ---------------------------------------------------------------------------- |
| vehicleid | The ID of the vehicle to get the health of. |
| &Float:health | A float variable in which to store the vehicle's health, passed by reference |
## ส่งคืน
1 - success
0 - failure (invalid vehicle ID).
The vehicle's health is stored in the referenced variable, not in the return value.
## ตัวอย่าง
```c
if (strcmp(cmdtext, "/repair", true) == 0)
{
new Float:health;
new veh = GetPlayerVehicleID(playerid);
GetVehicleHealth(veh, health);
if (health > 500)
{
return SendClientMessage(playerid, COLOR_RED, "Vehicle doesn't need repairing!");
}
SetVehicleHealth(veh, 1000);
SendClientMessage(playerid, COLOR_GREEN, "Vehicle repaired!");
}
```
## บันทึก
:::tip
Full vehicle health is 1000, however higher values are possible and increase the health of the vehicle. For more information on health values, see here.
:::
:::tip
A vehicle catches on fire when its health is below 250. It will explode a few seconds later.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetVehicleHealth: Set the health of a vehicle.
- GetPlayerHealth: Find out how much health a player has.
- GetPlayerArmour: Find out how much armour a player has.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehicleHealth.md",
"repo_id": "openmultiplayer",
"token_count": 633
} | 479 |
---
title: GivePlayerWeapon
description: Give a player a weapon with a specified amount of ammo.
tags: ["player"]
---
## คำอธิบาย
Give a player a weapon with a specified amount of ammo.
| Name | Description |
| -------- | ------------------------------------------- |
| playerid | The ID of the player to give a weapon to. |
| weaponid | The ID of the weapon to give to the player. |
| ammo | The amount of ammo to give to the player. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. This means the player is not connected.
## ตัวอย่าง
```c
GivePlayerWeapon(playerid, 26, 64); // Give playerid a sawn-off shotgun with 64 ammo
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerArmedWeapon: Set a player's armed weapon.
- GetPlayerWeapon: Check what weapon a player is currently holding.
| openmultiplayer/web/docs/translations/th/scripting/functions/GivePlayerWeapon.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GivePlayerWeapon.md",
"repo_id": "openmultiplayer",
"token_count": 354
} | 480 |
---
title: IsPlayerNPC
description: Check if a player is an actual player or an NPC.
tags: ["player", "npc"]
---
## คำอธิบาย
Check if a player is an actual player or an NPC.
| Name | Description |
| -------- | ------------------------------ |
| playerid | The ID of the player to check. |
## ส่งคืน
1: The player is an NPC.
0: The player is not an NPC.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid)
{
if (IsPlayerNPC(playerid))
{
SendClientMessageToAll(-1, "An NPC connected!");
return 1;
}
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [ConnectNPC](../../scripting/functions/ConnectNPC.md): Connect an NPC.
- [IsPlayerAdmin](../../scripting/functions/IsPlayerAdmin.md): Checks if a player is logged into RCON.
| openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerNPC.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsPlayerNPC.md",
"repo_id": "openmultiplayer",
"token_count": 367
} | 481 |
---
title: MovePlayerObject
description: Move a player object with a set speed.
tags: ["player"]
---
## คำอธิบาย
Move a player object with a set speed. Also supports rotation. Players/vehicles will surf moving objects.
| Name | Description |
| ----------- | ------------------------------------------------- |
| playerid | The ID of the player whose player-object to move. |
| objectid | The ID of the object to move. |
| Float:X | The X coordinate to move the object to. |
| Float:Y | The Y coordinate to move the object to. |
| Float:Z | The Z coordinate to move the object to. |
| Float:Speed | The speed at which to move the object. |
| Float:RotX | The final X rotation (optional). |
| Float:RotY | The final Y rotation (optional). |
| Float:RotZ | The final Z rotation (optional). |
| playerid | The player you associated this object to. |
| objectid | The objectid you want to move. |
| Float:X | The new X coordinate. |
| Float:Y | The new Y coordinate. |
| Float:Z | The new Z coordinate. |
| Float:Speed | The speed at which to move the object. |
## ส่งคืน
The time it will take for the object to move in milliseconds.
## ตัวอย่าง
```c
MovePlayerObject(playerid, objectid, 2001.195679, 1547.113892, 10);
```
## บันทึก
:::tip
If using the rotation parameters, the object must be moved (X/Y/Z). The object will interpolate the rotation from when the objects starts moving and when it stops. The parameters below are for 0.3d R2 and older versions and should be ignored if you run the latest version of SA-MP.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreatePlayerObject](../functions/CreatePlayerObject.md): Create an object for only one player.
- [DestroyPlayerObject](../functions/DestroyPlayerObject.md): Destroy a player object.
- [IsValidPlayerObject](../functions/IsValidPlayerObject.md): Checks if a certain player object is vaild.
- [StopPlayerObject](../functions/StopPlayerObject.md): Stop a player object from moving.
- [IsObjectMoving](../functions/IsObjectMoving.md): Check if the object is moving.
- [SetPlayerObjectPos](../functions/SetPlayerObjectPos.md): Set the position of a player object.
- [SetPlayerObjectRot](../functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../functions/GetPlayerObjectPos.md): Locate a player object.
- [GetPlayerObjectRot](../functions/GetPlayerObjectRot.md): Check the rotation of a player object.
- [AttachPlayerObjectToPlayer](../functions/AttachPlayerObjectToPlayer.md): Attach a player object to a player.
- [CreateObject](../functions/CreateObject.md): Create an object.
- [DestroyObject](../functions/DestroyObject.md): Destroy an object.
- [IsValidObject](../functions/IsValidObject.md): Checks if a certain object is vaild.
- [MoveObject](../functions/MoveObject.md): Move an object.
- [StopObject](../functions/StopObject.md): Stop an object from moving.
- [IsPlayerObjectMoving](../functions/IsPlayerObjectMoving.md): Check if the player object is moving.
- [SetObjectPos](../functions/SetObjectPos.md): Set the position of an object.
- [SetObjectRot](../functions/SetObjectRot.md): Set the rotation of an object.
- [GetObjectPos](../functions/GetObjectPos.md): Locate an object.
- [GetObjectRot](../functions/GetObjectRot.md): Check the rotation of an object.
- [AttachObjectToPlayer](../functions/AttachObjectToPlayer.md): Attach an object to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/MovePlayerObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/MovePlayerObject.md",
"repo_id": "openmultiplayer",
"token_count": 1370
} | 482 |
---
title: PlayerTextDrawBackgroundColor
description: Adjust the background color of a player-textdraw.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Adjust the background color of a player-textdraw.
| Name | Description |
| -------- | ------------------------------------------------------------------------- |
| playerid | The ID of the player whose player-textdraw to set the background color of |
| text | The ID of the player-textdraw to set the background color of |
| color | The color that the textdraw should be set to. |
## ส่งคืน
Note
If PlayerTextDrawSetOutline is used with size > 0, the outline color will match the color used in PlayerTextDrawBackgroundColor. Changing the value of color seems to alter the color used in PlayerTextDrawColor
## ตัวอย่าง
```c
new PlayerText:MyTextdraw;
public OnPlayerConnect(playerid)
{
MyTextdraw = CreatePlayerTextDraw(playerid, 320.0, 425.0, "This is an example textdraw");
PlayerTextDrawUseBox(playerid, MyTextdraw, 1);
PlayerTextDrawBackgroundColor(playerid, MyTextdraw, 0xFFFFFFFF); // Set the background color of MyTextdraw to white
return 1;
}
```
## บันทึก
:::tip
If PlayerTextDrawSetOutline is used with size > 0, the outline color will match the color used in PlayerTextDrawBackgroundColor. Changing the value of color seems to alter the color used in PlayerTextDrawColor
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- CreatePlayerTextDraw: Create a player-textdraw.
- PlayerTextDrawDestroy: Destroy a player-textdraw.
- PlayerTextDrawColor: Set the color of the text in a player-textdraw.
- PlayerTextDrawBoxColor: Set the color of a player-textdraw's box.
- PlayerTextDrawAlignment: Set the alignment of a player-textdraw.
- PlayerTextDrawFont: Set the font of a player-textdraw.
- PlayerTextDrawLetterSize: Set the letter size of the text in a player-textdraw.
- PlayerTextDrawTextSize: Set the size of a player-textdraw box (or clickable area for PlayerTextDrawSetSelectable).
- PlayerTextDrawSetOutline: Toggle the outline on a player-textdraw.
- PlayerTextDrawSetShadow: Set the shadow on a player-textdraw.
- PlayerTextDrawSetProportional: Scale the text spacing in a player-textdraw to a proportional ratio.
- PlayerTextDrawUseBox: Toggle the box on a player-textdraw.
- PlayerTextDrawSetString: Set the text of a player-textdraw.
- PlayerTextDrawShow: Show a player-textdraw.
- PlayerTextDrawHide: Hide a player-textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawBackgroundColor.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawBackgroundColor.md",
"repo_id": "openmultiplayer",
"token_count": 876
} | 483 |
---
title: PlayerTextDrawTextSize
description: Change the size of a player-textdraw (box if PlayerTextDrawUseBox is enabled and/or clickable area for use with PlayerTextDrawSetSelectable).
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Change the size of a player-textdraw (box if PlayerTextDrawUseBox is enabled and/or clickable area for use with PlayerTextDrawSetSelectable).
| Name | Description |
| -------- | -------------------------------------------------------------------------------------- |
| playerid | The ID of the player whose player-textdraw to set the size of |
| text | The ID of the player-textdraw to set the size of. |
| Float:x | The size on the X axis (left/right) following the same 640x480 grid as TextDrawCreate. |
| Float:y | The size on the Y axis (up/down) following the same 640x480 grid as TextDrawCreate. |
## ส่งคืน
The x and y have different meanings with different PlayerTextDrawAlignment values: 1 (left): they are the right-most corner of the box, absolute coordinates. 2 (center): they need to inverted (switch the two) and the x value is the overall width of the box. 3 (right): the x and y are the coordinates of the left-most corner of the box
1 (left): they are the right-most corner of the box, absolute coordinates.
2 (center): they need to inverted (switch the two) and the x value is the overall width of the box.
3 (right): the x and y are the coordinates of the left-most corner of the box
Using font type 4 (sprite) and 5 (model preview) converts X and Y of this function from corner coordinates to WIDTH and HEIGHT (offsets).
The TextDraw box starts 10.0 units up and 5.0 to the left as the origin (TextDrawCreate coordinate).
This function defines the clickable area for use with PlayerTextDrawSetSelectable, whether a box is shown or not.
## ตัวอย่าง
```c
MyTextDraw = CreatePlayerTextDraw(playerid, 100.0, 33.0, "Example TextDraw");
PlayerTextDrawTextSize(playerid, MyTextDraw, 2.0, 3.6);
```
## บันทึก
:::tip
The x and y have different meanings with different PlayerTextDrawAlignment values: 1 (left): they are the right-most corner of the box, absolute coordinates. 2 (center): they need to inverted (switch the two) and the x value is the overall width of the box. 3 (right): the x and y are the coordinates of the left-most corner of the box
Using font type 4 (sprite) and 5 (model preview) converts X and Y of this function from corner coordinates to WIDTH and HEIGHT (offsets). The TextDraw box starts 10.0 units up and 5.0 to the left as the origin (TextDrawCreate coordinate). This function defines the clickable area for use with PlayerTextDrawSetSelectable, whether a box is shown or not.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- CreatePlayerTextDraw: Create a player-textdraw.
- PlayerTextDrawDestroy: Destroy a player-textdraw.
- PlayerTextDrawColor: Set the color of the text in a player-textdraw.
- PlayerTextDrawBoxColor: Set the color of a player-textdraw's box.
- PlayerTextDrawBackgroundColor: Set the background color of a player-textdraw.
- PlayerTextDrawAlignment: Set the alignment of a player-textdraw.
- PlayerTextDrawFont: Set the font of a player-textdraw.
- PlayerTextDrawLetterSize: Set the letter size of the text in a player-textdraw.
- PlayerTextDrawSetOutline: Toggle the outline on a player-textdraw.
- PlayerTextDrawSetShadow: Set the shadow on a player-textdraw.
- PlayerTextDrawSetProportional: Scale the text spacing in a player-textdraw to a proportional ratio.
- PlayerTextDrawUseBox: Toggle the box on a player-textdraw.
- PlayerTextDrawSetString: Set the text of a player-textdraw.
- PlayerTextDrawShow: Show a player-textdraw.
- PlayerTextDrawHide: Hide a player-textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawTextSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawTextSize.md",
"repo_id": "openmultiplayer",
"token_count": 1240
} | 484 |
---
title: SendDeathMessage
description: Adds a death to the 'killfeed' on the right-hand side of the screen for all players.
tags: []
---
## คำอธิบาย
Adds a death to the 'killfeed' on the right-hand side of the screen for all players.
| Name | Description |
| -------- | --------------------------------------------------------------------------------------------------------------------------- |
| killer | The ID of the killer (can be INVALID_PLAYER_ID). |
| playerid | The ID of the player that died. |
| weapon | The reason (not always a weapon) for the victim's death. Special icons can also be used (ICON_CONNECT and ICON_DISCONNECT). |
## ส่งคืน
This function always returns 1, even if the function fails to execute. The function fails to execute (no death message shown) if 'playerid' is invalid. If 'reason' is invalid, a generic skull-and-crossbones icon is shown. 'killerid' being invalid (INVALID_PLAYER_ID) is valid.
## ตัวอย่าง
```c
public OnPlayerDeath(playerid, killerid, WEAPON:reason)
{
SendDeathMessage(killerid, playerid, reason);
return 1;
}
```
## บันทึก
:::tip
Death messages can be cleared by using a valid player ID for 'playerid' that is not connected. To show a death message for just a single player, use SendDeathMessageToPlayer. You can use NPCs to create your own custom death reasons.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SendDeathMessageToPlayer: Add a kill to the death list for a player.
- OnPlayerDeath: Called when a player dies.
| openmultiplayer/web/docs/translations/th/scripting/functions/SendDeathMessage.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SendDeathMessage.md",
"repo_id": "openmultiplayer",
"token_count": 786
} | 485 |
---
title: SetObjectMaterial
description: Replace the texture of an object with the texture from another model in the game.
tags: []
---
## คำอธิบาย
Replace the texture of an object with the texture from another model in the game.
| Name | Description |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| objectid | The ID of the object to change the texture of |
| materialindex | The material index on the object to change (0 to 15) |
| modelid | The modelid on which the replacement texture is located. Use 0 for alpha. Use -1 to change the material color without altering the texture. |
| txdname | The name of the txd file which contains the replacement texture (use "none" if not required) |
| texturename | The name of the texture to use as the replacement (use "none" if not required) |
| materialcolor | The object color to set, as an integer or hex in ARGB color format. Using 0 keeps the existing material color. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext,"/mycommand",true))
{
new Float:X, Float:Y, Float:Z;
new myobject;
GetPlayerPos(playerid, X, Y, Z);
myobject = CreateObject(19371, X, Y, Z+0.5, 0.0, 0.0, 0.0, 300.0);
SetObjectMaterial(myobject, 0, 19341, "egg_texts", "easter_egg01", 0xFFFFFFFF);
//Replaces the texture of our object with the texture of object 19341
return 1;
}
return 0;
}
```
## บันทึก
:::tip
Vertex lighting of the object will disappear if material color is changed.
:::
:::warning
You MUST use ARGB color format, not RGBA like used in client messages etc.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerObjectMaterial: Replace the texture of a player object with the texture from another model in the game.
- SetObjectMaterialText: Replace the texture of an object with text.
- Ultimate Creator by Nexius
- Fusez's Map Editor by RedFusion
| openmultiplayer/web/docs/translations/th/scripting/functions/SetObjectMaterial.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetObjectMaterial.md",
"repo_id": "openmultiplayer",
"token_count": 1186
} | 486 |
---
title: SetPlayerCheckpoint
description: Sets a checkpoint (red cylinder) for a player.
tags: ["player", "checkpoint"]
---
## คำอธิบาย
Sets a checkpoint (red cylinder) for a player. Also shows a red blip on the radar. When players enter a checkpoint, OnPlayerEnterCheckpoint is called and actions can be performed.
| Name | Description |
| ---------- | -------------------------------------------------- |
| playerid | The ID of the player for whom to set a checkpoint. |
| Float:x | The X coordinate to set the checkpoint at. |
| Float:y | The Y coordinate to set the checkpoint at. |
| Float:z | The Z coordinate to set the checkpoint at. |
| Float:size | The size of the checkpoint. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player specified does not exist.
## ตัวอย่าง
```c
// In this example the player's checkpoint will be set when they spawn.
// On entering the checkpoint they will receive $1000 and the checkpoint will be disabled.
new bool:onCheck[MAX_PLAYERS];
public OnPlayerSpawn(playerid)
{
SetPlayerCheckpoint(playerid, 1982.6150, -220.6680, -0.2432, 3.0);
onCheck[playerid] = true;
return 1;
}
public OnPlayerEnterCheckpoint(playerid)
{
if (onCheck[playerid]) // if it's true
{
GivePlayerMoney(playerid, 1000);
DisablePlayerCheckpoint(playerid);
onCheck[playerid] = false;
}
return 1;
}
```
## บันทึก
:::warning
Checkpoints are asynchronous, meaning only one can be shown at a time. To 'stream' checkpoints (only show them when players are close enough), use a checkpoint streamer.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- DisablePlayerCheckpoint: Disable the player's current checkpoint.
- IsPlayerInCheckpoint: Check if a player is in a checkpoint.
- SetPlayerRaceCheckpoint: Create a race checkpoint for a player.
- DisablePlayerRaceCheckpoint: Disable the player's current race checkpoint.
- IsPlayerInRaceCheckpoint: Check if a player is in a race checkpoint.
- OnPlayerEnterCheckpoint: Called when a player enters a checkpoint.
- OnPlayerLeaveCheckpoint: Called when a player leaves a checkpoint.
- OnPlayerEnterRaceCheckpoint: Called when a player enters a race checkpoint.
- OnPlayerLeaveRaceCheckpoint: Called when a player leaves a race checkpoint.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerCheckpoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerCheckpoint.md",
"repo_id": "openmultiplayer",
"token_count": 850
} | 487 |
---
title: SetPlayerPos
description: Set a player's position.
tags: ["player"]
---
## คำอธิบาย
Set a player's position.
| Name | Description |
| -------- | -------------------------------------------- |
| playerid | The ID of the player to set the position of. |
| Float:x | The X coordinate to position the player at. |
| Float:y | The Y coordinate to position the player at. |
| Float:z | The Z coordinate to position the player at. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player specified does not exist.
## ตัวอย่าง
```c
// Teleports players to the center of San Andreas when they type /middle
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext, "/middle", true))
{
SetPlayerPos(playerid, 0.0, 0.0, 3.0);
return 1;
}
return 0;
}
```
## บันทึก
:::tip
Using this function on a player in a vehicle will instantly remove them from the vehicle. Useful for quickly ejecting players.
:::
:::tip
When setting a player's position to an interior, their interior must be set also.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerPosFindZ: Set a player's position and find the ground.
- GetPlayerPos: Get a player's position.
- SetVehiclePos: Set the position of a vehicle.
- GetVehiclePos: Get the position of a vehicle.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerPos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerPos.md",
"repo_id": "openmultiplayer",
"token_count": 545
} | 488 |
---
title: SetSVarInt
description: Set an integer server variable.
tags: []
---
:::warning
This function was added in SA-MP 0.3.7 R2 and will not work in earlier versions!
:::
## คำอธิบาย
Set an integer server variable.
| Name | Description |
| --------- | -------------------------------- |
| varname[] | The name of the server variable. |
| int_value | The integer to be set. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The variable name is null or over 40 characters.
## ตัวอย่าง
```c
// set "Version"
SetSVarInt("Version", 37);
// will print version that server has
printf("Version: %d", GetSVarInt("Version"));
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetSVarInt: Get a player server as an integer.
- SetSVarString: Set a string for a server variable.
- GetSVarString: Get the previously set string from a server variable.
- SetSVarFloat: Set a float for a server variable.
- GetSVarFloat: Get the previously set float from a server variable.
- DeleteSVar: Delete a server variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarInt.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetSVarInt.md",
"repo_id": "openmultiplayer",
"token_count": 420
} | 489 |
---
title: SetVehicleVirtualWorld
description: Sets the 'virtual world' of a vehicle.
tags: ["vehicle"]
---
## คำอธิบาย
Sets the 'virtual world' of a vehicle. Players will only be able to see vehicles in their own virtual world.
| Name | Description |
| --------- | -------------------------------------------------- |
| vehicleid | The ID of vehicle to set the virtual world of. |
| worldid | The ID of the virtual world to put the vehicle in. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
SetVehicleVirtualWorld(GetPlayerVehicleID(playerid), 10);
SetPlayerVirtualWorld(playerid, 10);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetVehicleVirtualWorld: Check what virtual world a vehicle is in.
- SetPlayerVirtualWorld: Set the virtual world of a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleVirtualWorld.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleVirtualWorld.md",
"repo_id": "openmultiplayer",
"token_count": 350
} | 490 |
---
title: TextDrawAlignment
description: Set the alignment of text in a text draw.
tags: ["textdraw"]
---
## คำอธิบาย
Set the alignment of text in a text draw.
| Name | Description |
| --------- | ----------------------------------------------- |
| Text:text | The ID of the textdraw to set the alignment of. |
| alignment | 1-left 2-centered 3-right. |
## ส่งคืน
Note
For alignment 2 (center) the x and y values of TextSize need to be swapped, see notes at TextDrawTextSize, also position coordinate become position of center of textdraw and not left/top edges.
## ตัวอย่าง
```c
new Text:MyTextdraw;
public OnGameModeInit()
{
new Text:MyTextdraw = TextDrawCreate(320.0, 425.0, "This is an example textdraw");
TextDrawAlignment(MyTextdraw, 2); // Align the textdraw text in the center
return 1;
}
```
## บันทึก
:::tip
If the textdraw is already shown, it must be re-shown (TextDrawShowForAll/TextDrawShowForPlayer) to show the changes of this function.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw.
- [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw.
- [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw.
- [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw.
- [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw.
- [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw.
- [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw.
- [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box.
- [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline.
- [TextDrawSetShadow](../functions/TextDrawSetShadow.md): Toggle shadows on a textdraw.
- [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio.
- [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not.
- [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw.
- [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player.
- [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player.
- [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
- [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawAlignment.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawAlignment.md",
"repo_id": "openmultiplayer",
"token_count": 947
} | 491 |
---
title: TextDrawSetShadow
description: Sets the size of a textdraw's text's shadow.
tags: ["textdraw"]
---
## คำอธิบาย
Sets the size of a textdraw's text's shadow.
| Name | Description |
| ---- | ------------------------------------------------------------------------------------------------------- |
| text | The ID of the textdraw to set the shadow size of. |
| size | The size of the shadow. 1 is generally used for a normal shadow size. 0 disables the shadow completely. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The textdraw does not exist.
## ตัวอย่าง
```c
new Text:MyTextdraw;
public OnGameModeInit()
{
MyTextDraw = TextDrawCreate(100.0, 33.0, "Example TextDraw");
TextDrawSetShadow(MyTextDraw, 1);
return 1;
}
```
## บันทึก
:::tip
The shadow can be cut by the box area if the size is set too big for the area.
:::
:::tip
If you want to change the shadow of a textdraw that is already shown, you don't have to recreate it. Simply use TextDrawShowForPlayer/TextDrawShowForAll after modifying the textdraw and the change will be visible.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [TextDrawCreate](../functions/TextDrawCreate.md): Create a textdraw.
- [TextDrawDestroy](../functions/TextDrawDestroy.md): Destroy a textdraw.
- [TextDrawColor](../functions/TextDrawColor.md): Set the color of the text in a textdraw.
- [TextDrawBoxColor](../functions/TextDrawBoxColor.md): Set the color of the box in a textdraw.
- [TextDrawBackgroundColor](../functions/TextDrawBackgroundColor.md): Set the background color of a textdraw.
- [TextDrawAlignment](../functions/TextDrawAlignment.md): Set the alignment of a textdraw.
- [TextDrawFont](../functions/TextDrawFont.md): Set the font of a textdraw.
- [TextDrawLetterSize](../functions/TextDrawLetterSize.md): Set the letter size of the text in a textdraw.
- [TextDrawTextSize](../functions/TextDrawTextSize.md): Set the size of a textdraw box.
- [TextDrawSetOutline](../functions/TextDrawSetOutline.md): Choose whether the text has an outline.
- [TextDrawSetProportional](../functions/TextDrawSetProportional.md): Scale the text spacing in a textdraw to a proportional ratio.
- [TextDrawUseBox](../functions/TextDrawUseBox.md): Toggle if the textdraw has a box or not.
- [TextDrawSetString](../functions/TextDrawSetString.md): Set the text in an existing textdraw.
- [TextDrawShowForPlayer](../functions/TextDrawShowForPlayer.md): Show a textdraw for a certain player.
- [TextDrawHideForPlayer](../functions/TextDrawHideForPlayer.md): Hide a textdraw for a certain player.
- [TextDrawShowForAll](../functions/TextDrawShowForAll.md): Show a textdraw for all players.
- [TextDrawHideForAll](../functions/TextDrawHideForAll.md): Hide a textdraw for all players.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetShadow.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawSetShadow.md",
"repo_id": "openmultiplayer",
"token_count": 1056
} | 492 |
---
title: acos
description: .
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
.
| Name | Description |
| ---- | ----------- |
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/acos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/acos.md",
"repo_id": "openmultiplayer",
"token_count": 127
} | 493 |
---
title: db_get_mem_handle
description: Get memory handle for an SQLite database that was opened with db_open.
tags: ["sqlite"]
---
:::warning
This function starts with lowercase letter.
This function was added in SA-MP 0.3.7 R1 and will not work in earlier versions!
:::
## คำอธิบาย
Get memory handle for an SQLite database that was opened with db_open.
| Name | Description |
| ----- | ----------------------------------------------------------- |
| DB:db | The index of the database connection (returned by db_open). |
## ส่งคืน
Returns the memory handle for a specified database.
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- db_open: Open a connection to an SQLite database
- db_close: Close the connection to an SQLite database
- db_query: Query an SQLite database
- db_free_result: Free result memory from a db_query
- db_num_rows: Get the number of rows in a result
- db_next_row: Move to the next row
- db_num_fields: Get the number of fields in a result
- db_field_name: Returns the name of a field at a particular index
- db_get_field: Get content of field with specified ID from current result row
- db_get_field_assoc: Get content of field with specified name from current result row
- db_get_field_int: Get content of field as an integer with specified ID from current result row
- db_get_field_assoc_int: Get content of field as an integer with specified name from current result row
- db_get_field_float: Get content of field as a float with specified ID from current result row
- db_get_field_assoc_float: Get content of field as a float with specified name from current result row
- db_get_mem_handle: Get memory handle for an SQLite database that was opened with db_open.
- db_get_result_mem_handle: Get memory handle for an SQLite query that was executed with db_query.
- db_debug_openfiles
- db_debug_openresults
| openmultiplayer/web/docs/translations/th/scripting/functions/db_get_mem_handle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/db_get_mem_handle.md",
"repo_id": "openmultiplayer",
"token_count": 621
} | 494 |
---
title: floatabs
description: This function returns the absolute value of float.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function returns the absolute value of float.
| Name | Description |
| ----------- | --------------------------------------------- |
| Float:value | The float value to get the absolute value of. |
## ส่งคืน
The absolute value of the float (as a float value).
## ตัวอย่าง
```c
floatabs(47.0); // This will return 47.0.
floatabs(-47.0); // This will return the same.
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/floatabs.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatabs.md",
"repo_id": "openmultiplayer",
"token_count": 291
} | 495 |
---
title: fopen
description: Open a file (to read from or write to).
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Open a file (to read from or write to).
| Name | Description |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| name[] | The path to the file to open (if just a filename is specified, it will open the file with the name specified in the 'scriptfiles' folder). |
| mode | The mode to open the file with (default: io_readwrite). |
## ส่งคืน
Returns the file handle. This handle is used for reading and writing. 0 if failed to open file.
## ตัวอย่าง
```c
// Open "file.txt" in "read only" mode
new File:handle = fopen("file.txt", io_read),
// Initialize "buf"
buf[128];
// Check, if the file is opened
if (handle)
{
// Success
// Read the whole file
while(fread(handle, buf)) print(buf);
// Close the file
fclose(handle);
}
else
{
// Error
print("The file \"file.txt\" does not exists, or can't be opened.");
}
// Open "file.txt" in "write only" mode
new File:handle = fopen("file.txt", io_write);
// Check, if file is open
if (handle)
{
// Success
// Write "I just wrote here!" into this file
fwrite(handle, "I just wrote here!");
// Close the file
fclose(handle);
}
else
{
// Error
print("Failed to open file \"file.txt\".");
}
// Open "file.txt" in "read and write" mode
new File:handle = fopen("file.txt"),
// Initialize "buf"
buf[128];
// Check, if file is open
if (handle)
{
// Success
// Read the whole file
while(fread(handle, buf)) print(buf);
// Set the file pointer to the first byte
fseek(handle, _, seek_begin);
// Write "I just wrote here!" into this file
fwrite(handle, "I just wrote here!");
// Close the file
fclose(handle);
}
else
{
// Error
print("The file \"file.txt\" does not exists, or can't be opened.");
}
// Open "file.txt" in "append only" mode
new File:handle = fopen("file.txt", io_append);
// Check, if file is open
if (handle)
{
// Success
// Append "This is a text.\r\n"
fwrite(handle, "This is a test.\r\n");
// Close the file
fclose(handle);
}
else
{
// Error
print("Failed to open file \"file.txt\".");
}
```
```
io_read Reads from the file.
io_write Write in the file, or create the file if it does not exist. Erases all existing contents.
io_readwrite Reads the file or creates it if it doesn't already exist.
io_append Appends (adds) to file, write-only. If the file does not exist, it is created.
```
## บันทึก
:::warning
If you use io_read and the file doesn't exist, it will return a NULL reference. Using invalid references on file functions will crash your server!
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [fopen](../functions/fopen): Open a file.
- [fclose](../functions/fclose): Close a file.
- [ftemp](../functions/ftemp): Create a temporary file stream.
- [fremove](../functions/fremove): Remove a file.
- [fwrite](../functions/fwrite): Write to a file.
- [fread](../functions/fread): Read a file.
- [fputchar](../functions/fputchar): Put a character in a file.
- [fgetchar](../functions/fgetchar): Get a character from a file.
- [fblockwrite](../functions/fblockwrite): Write blocks of data into a file.
- [fblockread](../functions/fblockread): Read blocks of data from a file.
- [fseek](../functions/fseek): Jump to a specific character in a file.
- [flength](../functions/flength): Get the file length.
- [fexist](../functions/fexist): Check, if a file exists.
- [fmatch](../functions/fmatch): Check, if patterns with a file name matches.
| openmultiplayer/web/docs/translations/th/scripting/functions/fopen.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/fopen.md",
"repo_id": "openmultiplayer",
"token_count": 1559
} | 496 |
---
title: max
description: .
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
.
| Name | Description |
| ---- | ----------- |
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/max.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/max.md",
"repo_id": "openmultiplayer",
"token_count": 126
} | 497 |
---
title: strlen
description: Get the length of a string.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Get the length of a string.
| Name | Description |
| -------------- | -------------------------------- |
| const string[] | The string to get the length of. |
## ส่งคืน
The length of the string as an integer.
## ตัวอย่าง
```c
new stringLength = strlen("This is an example string."); // stringLength is now set to 26
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- strcmp: Compare two strings to check if they are the same.
- strfind: Search for a string in another string.
- strtok: Get the next 'token' (word/parameter) in a string.
- strdel: Delete part of a string.
- strins: Insert text into a string.
- strmid: Extract part of a string into another string.
- strpack: Pack a string into a destination string.
- strval: Convert a string into an integer.
- strcat: Concatenate two strings into a destination reference.
| openmultiplayer/web/docs/translations/th/scripting/functions/strlen.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/strlen.md",
"repo_id": "openmultiplayer",
"token_count": 392
} | 498 |
---
title: "Pawn Style Guide"
description: A short guide on the generally accepted naming conventions and other aspects of Pawn source code to aid easier communication of intent and streamline debugging and sharing of code.
---
This document is a short guide on the generally accepted naming conventions and other aspects of Pawn source code to aid easier communication of intent and streamline debugging and sharing of code.
See also:
- [Modern Pawn](https://github.com/Southclaws/sampctl/wiki/Modern-Pawn)
- [Pawn Package](https://github.com/Southclaws/sampctl/wiki/Packages)
## Terminology
### Statement
A statement is a piece of code that imperatively tells the host program to do something. A statement is a valid piece of code that yields some result.
```c
a = b + c;
```
This is a statement composed of a variable being assigned the result of an [#Expression].
```c
SetPlayerColor(playerid, 0xFF4700FF);
```
This is a statement telling the program to call a function with some arguments.
```c
x + 8
```
This is _not_ a statement as the result is not used anywhere, this is just an [#Expression].
### Compound Statement
A compound statement is a collection of statements surrounded by braces.
```c
{
new message[] = "hi!";
print(message);
}
```
This is a compound statement composed of two statements.
```c
if (a == b)
{
print("hello!");
}
```
This is a compound statement with an `if` condition, this is usually referred to as an "if statement".
```c
return Function1(), Function2(), Function3();
```
This is _not_ a compound statement, it's a chain of statements separated by commas. This form of chaining statements is considered bad practice.
### Expression
An expression is a piece of syntax that yields a value, it's not a valid statement unless the yielded value is used in some way.
Expressions are often composed to form statements.
```c
a + b
```
This is a simple addition expression that takes two values and applies the add operator to them.
## Guidelines
### Braces
Allman braces are preferred:
```pawn
function()
{
//
}
```
However, if you can't shake the muscle memory, K&R braces are also valid Pawn:
```pawn
function() {
//
}
```
### Switches
Switches must use two indent levels, one for the `switch` block and another for each `case` statement or compound statement.
```pawn
switch (variable)
{
case 0:
return 0;
case 1:
return 1;
case 2:
return 2;
default:
return -1;
}
```
```pawn
switch (variable)
{
case 0:
{
// code...
return 0;
}
case 1:
{
// code...
return 1;
}
case 2:
{
// code...
return 2;
}
default:
{
// code...
return -1;
}
}
```
### Compound Statements (Blocks)
Blocks must always use braces, even if only a single line of code exists within a block. This applies to all levels including functions.
```pawn
func()
{
singleLineExpr();
}
```
```pawn
func()
{
if ()
{
singleLineExpr();
}
}
```
```pawn
func()
{
if ()
{
singleLineExpr();
}
else if ()
{
//
}
else
{
//
}
}
```
### Naming
#### Functions
Functions must be named with `PascalCase`.
#### Global Variables
Global variables must always use `g` prefixed PascalCase, so `gVariableName` and should generally always be `static`.
Constant globals must use `SCREAMING_SNAKE_CASE`.
#### Local Variables
Local variables must always use `camelCase` and must never use single letter names, apart from:
- `i`, `j`, `k`, etc in `for` loops
- `x`, `y`, `z`, etc in mathematical contexts
#### Enumerators
Enumerators, if named, must be prefixed with `E_` and use `SCREAMING_SNAKE_CASE`. The one exception is when avoiding a `Index tag mismatch` warning, in which case an `e_` prefix may be used. `SCREAMING_SNAKE_CASE` must still be used even with the lower case `e_` prefix.
Enumerator fields must also be `SCREAMING_SNAKE_CASE` and use the enumerator name as a prefix.
```pawn
static enum E_PLAYER {
E_PLAYER_CASH,
Float:E_PLAYER_HEALTH,
}
```
To avoid index tag warnings in some cases:
```pawn
static enum e_PLAYER {
e_PLAYER_CASH,
Float:e_PLAYER_HEALTH,
}
```
Enumerators must always be declared `static` unless used outside the module.
#### Macros and Pre-Processor Definitions
Macros must always use `SCREAMING_SNAKE_CASE` regardless of their usage.
Pre-Processor definitions (constant definitions) must also use `SCREAMING_SNAKE_CASE`.
This helps differentiate between variables and constants as well as functions and macros.
It's generally advised to avoid inventing new syntactical elements in order to prevent confusion among newcomers as to which words are part of the language and which words are from libraries.
However, some older libraries do this and cannot change because of backwards compatibility.
### Documentation
Always document exported functions with a simple line comment in the format `// FunctionName does X, Y and Z and returns A` where the first word is the name of the function itself followed by a brief description of what it does. No need to waste time describing each individual parameter. For example:
```pawn
// LoadPlayerAccount is called to initiate the account load process. This
// function will trigger HTTP calls to get player data, it will display dialogs
// to the player and eventually, once the process has completed, the event
// `OnPlayerLogin` is emitted on success. On failure, the player is kicked.
stock Error:LoadPlayerAccount(playerid)
{
// code...
}
```
Each package should have a `README.md` and, if necessary, each module should have a comment on the very first line describing what that module provides.
| openmultiplayer/web/docs/translations/th/scripting/language/Style.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/language/Style.md",
"repo_id": "openmultiplayer",
"token_count": 1843
} | 499 |