text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
---
title: fputchar
description: Napišite jedan znak u datoteku.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Napišite jedan znak u datoteku.
| Ime | Deskripcija |
| ------ | ---------------------------------------------------------------- |
| handle | Upravitelj datoteke za upotrebu, otvorila je fopen () |
| value | Ovaj parametar nema koristi, samo ga ostavite na "0". |
| utf8 | Ako je tačno, čitajte znak kao UTF-8, inače kao prošireni ASCII. |
## Returns
Ova funkcija ne returna (vraća) nikakve posebne vrijednosti.
## Primjeri
```c
// Otvorite "file.txt" u "write only" načinu (samo pisanje)
new File:handle = fopen("file.txt", io_write);
if (handle)
{
// Uspješno
// Ispiši karakter "e" u "file.txt"
fputchar(handle, 'e', false);
// Zatvori "file.txt"
fclose(handle);
}
else
{
// Error
print("Nesupješno otvaranje \"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.
- [fclose](fclose): Zatvori 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/fputchar.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/fputchar.md",
"repo_id": "openmultiplayer",
"token_count": 921
} | 361 |
---
title: max
description: .
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Funkcija korištena za usporedbu vrijednosti.
| Ime | Deskripcija |
| --- | -------------------------- |
| a | Vrijednost a za uporediti. |
| b | Vrijednost b za uporediti. |
## Returns
Returna/vraća najmanji od a i b. Ako su oba ekvivalentna, vraća se a.
## Primjeri
```c
//S obzirom da je b veće rezultat će biti 5.
public OnGameModeInit()
{
new
a, b, rezultat;
a = 5;
b = 10;
rezultat = max(a,b);
printf ("max(a,b) =", param, rezultat);
return 0;
}
```
## Srodne Funkcije
- [min](min): Uporedite i dobiti minimalnu vrijednost.
- [max](max): Uporedite i dobiti maksimalnu vrijednost.
| openmultiplayer/web/docs/translations/bs/scripting/functions/max.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/max.md",
"repo_id": "openmultiplayer",
"token_count": 378
} | 362 |
---
title: strlen
description: Dobij dužinu stringa.
tags: []
---
:::warning
Ova funkcija započinje malim slovom.
:::
## Deskripcija
Dobij dužinu stringa.
| Ime | Deskripcija |
| -------------- | ------------------------ |
| const string[] | String za dobiti dužinu. |
## Returns
Dužina stringa kao cijeli broj.
## Primjeri
```c
new stringLength = strlen("Ovo je primjer stringa."); // stringLength je sata postavljenja na 24
```
## Srodne Funkcije
- [strcmp](strcmp): Uporedi dva stringa kako bi provjerio da li su isti.
- [strfind](strfind): Pretraži string u drugom stringu.
- [strins](../function/strins): Unesi tekst u string.
- [strmid](strmid): Izdvoji dio stringa u drugi string.
- [strpack](strpack): Upakuj string u odredišni string.
- [strval](strval): Pretvori string u cijeli broj.
- [strcat](strcat): Spojite dva stringa u odredišnu referencu.
- [strdel](strdel): Obriši dio stringa.
| openmultiplayer/web/docs/translations/bs/scripting/functions/strlen.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/bs/scripting/functions/strlen.md",
"repo_id": "openmultiplayer",
"token_count": 385
} | 363 |
---
title: OnEnterExitModShop
description: Das Callback wird aufgerufen, wenn ein Spieler eine Tuningwerkstatt betritt oder verlässt.
tags: []
---
## Beschreibung
Das Callback wird aufgerufen, wenn ein Spieler eine Tuningwerkstatt betritt oder verlässt.
| Name | Beschreibung |
| ---------- | ---------------------------------------------------------------------------- |
| playerid | Die ID des Spielers |
| enterexit | 1 bei Betreten 0 bei Verlassen der Werkstatt |
| interiorid | Interior ID der Tuningwerkstatt die betreten wird (oder 0 beim Verlassen) |
## Rückgabe(return value)
Dieses Callback wird in Filterscripts immer zuerst aufgerufen.
## Beispiele
```c
public OnEnterExitModShop(playerid, enterexit, interiorid)
{
if (enterexit == 0) // Ist enterexit 0, verlässt der Spieler die Werkstatt
{
SendClientMessage(playerid, COLOR_WHITE, "Schönes Auto! Der Umbau kostet dich $100.");
GivePlayerMoney(playerid, -100);
}
return 1;
}
```
## Anmerkungen
:::warning
Bekannte Bugs: Spieler kollidieren wenn sie sich zusammen in einer Werkstatt befinden.
:::
## Ähnliche Funktionen
- [AddVehicleComponent](../functions/AddVehicleComponent): Füge einem Fahrzeug ein Component(Tuning-Teil) hinzu.
| openmultiplayer/web/docs/translations/de/scripting/callbacks/OnEnterExitModShop.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/de/scripting/callbacks/OnEnterExitModShop.md",
"repo_id": "openmultiplayer",
"token_count": 599
} | 364 |
---
título: OnActorStreamOut
descripción: Este callback se llama cuando un actor se deja de cargar (se hace invisible) por el cliente de un jugador.
tags: []
---
<VersionWarnES name='callback' version='SA-MP 0.3.7' />
## Descripción
Este callback se llama cuando un actor se deja de transmitir por el cliente de un jugador.
| Nombre | Descripción |
| ----------- | -------------------------------------------------------------- |
| actorid | El ID del actor que dejó de ser transmitido por el jugador. |
| forplayerid | El ID del jugador que dejó de transmitir al actor. |
## Devoluciones
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnActorStreamOut(actorid, forplayerid)
{
new string[40];
format(string, sizeof(string), "El actor %d dejó de ser transmitido a tu jugador.", actorid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## Notas
<TipNPCCallbacksES />
## Funciones Relacionadas
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnActorStreamOut.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnActorStreamOut.md",
"repo_id": "openmultiplayer",
"token_count": 402
} | 365 |
---
título: OnPlayerCommandText
descripción: Este callback se llama cuando un jugador ingresa un comando dentro de la ventana de chat del cliente.
tags: ["player"]
---
## Descripción
Este callback se llama cuando un jugador ingresa un comando dentro de la ventana de chat del cliente. Los comandos son todo lo que empieza con una barra inclinada "/", por ejemplo, /ayuda.
| Nombre | Descripción |
| --------- | ------------------------------------------------------------- |
| playerid | El ID del jugador que ingresó un comando. |
| cmdtext[] | El comando que fue ingresado (incluyendo la barra inclinada). |
## 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 OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/ayuda", true))
{
SendClientMessage(playerid, -1, "SERVER: Este es el comando /ayuda !");
return 1;
// Devolviendo 1 informa al servidor que el comando fue procesado.
// OnPlayerCommandText no se llamará en otros scripts.
}
return 0;
// Devolviendo 0 informa al servidor que el comando no fue procesado por este script.
// OnPlayerCommandText va a ser llamado en otros scripts hasta que uno devuelva 1.
// Si ningún script devuelve 1, el mensaje 'SERVER: Unkown Command' va a ser mostrado al jugador.
}
```
## Notas
<TipNPCCallbacksES />
## Funciones Relacionadas
- [SendRconCommand](../functions/SendRconCommand): Envía un comando RCON vía script.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerCommandText.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerCommandText.md",
"repo_id": "openmultiplayer",
"token_count": 646
} | 366 |
---
título: OnPlayerLeaveCheckpoint
descripción: Este callback se llama cuando un jugador sale del checkpoint establecido a él por SetPlayerCheckpoint.
tags: ["player", "checkpoint"]
---
## Descripción
Este callback se llama cuando un jugador sale del checkpoint establecido a él por SetPlayerCheckpoint. Sólo se puede establecer un checkpoint al mismo tiempo al jugador.
| Nombre | Descripción |
| -------- | ------------------------------------------------ |
| playerid | El ID del jugador que salió de su checkpoint. |
## Devoluciones
Siempre se llama primero en filterscripts.
## Ejemplos
```c
public OnPlayerLeaveCheckpoint(playerid)
{
printf("El jugador %i salió de un checkpoint!", playerid);
return 1;
}
```
## Notas
<TipNPCCallbacksES />
## Funciones Relacionadas
- [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): Crear un checkpoint a un jugador.
- [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): Deshabilitar el checkpoint actual de un jugador.
- [IsPlayerInCheckpoint](../functions/IsPlayerInCheckpoint): Comprobar si el jugador está en un checkpoint.
- [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): Crear un checkpoint de carreras a un jugador.
- [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): Deshabilitar el checkpoint de carreras actual del jugador.
- [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): Comprobar si el jugador está en un checkpoint de carreras.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerLeaveCheckpoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerLeaveCheckpoint.md",
"repo_id": "openmultiplayer",
"token_count": 494
} | 367 |
---
título: OnPlayerWeaponShot
descripción: Este callback se llama cuando un jugador efectúa un disparo de un arma.
tags: ["player"]
---
## Descripción
Este callback se llama cuando un jugador efectúa un disparo de un arma. Solo soporta armas que usen balas. Sólo soporta drive-by por parte del pasajero (no drive-by del conductor, tampoco disparos de seasparrow / hunter).
| Nombre | Descripción |
|-------------------------|----------------------------------------------------------------------------------------------------------------------------|
| playerid | El ID del jugador que disparó un arma. |
| WEAPON:weaponid | El ID del [arma](../resources/weaponids) que usó el jugador para disparar. |
| BULLET_HIT_TYPE:hittype | El [tipo](../resources/bullethittypes) de cosa a la que impactó el disparo (nada, jugador, vehículo, o objeto de jugador). |
| hitid | El ID del jugador, vehículo, o objeto de jugador al que el disparo impactó. |
| Float:fX | La coordenada X en la que golpeó el disparo. |
| Float:fY | La coordenada Y en la que golpeó el disparo. |
| Float:fZ | La coordenada Z en la que golpeó el disparo. |
## 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 OnPlayerWeaponShot(playerid, WEAPON:weaponid, BULLET_HIT_TYPE:hittype, hitid, Float:fX, Float:fY, Float:fZ)
{
new szString[144];
format(szString, sizeof(szString), "Arma %i disparada. hittype: %i hitid: %i pos: %f, %f, %f", weaponid, hittype, hitid, fX, fY, fZ);
SendClientMessage(playerid, -1, szString);
return 1;
}
```
## Notas
:::tip
Este callback sólo se llama cuando lag compensation está activado. Si hittype es:
- `BULLET_HIT_TYPE_NONE`: Los parámetros fX, fY y fZ son coordenadas normales, devolverá 0.0 para coordenadas si nada fue impactado (ej. objeto lejano que la bala no puede alcanzar);
- Otros: Los parámetros fX, fY y fZ son compensaciones relativas al hitid.
:::
:::tip
[GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors) puede ser usado en este callback para obtener información vectorial más detallada de la bala.
:::
:::warning
Bugs Conocido(s):
- No se llama si disparaste en un vehículo como el conductor o si estás mirando hacia atrás con el apuntado activado (disparando hacia el aire).
- Se llama como `BULLET_HIT_TYPE_VEHICLE` con el hitid correcto (el vehicleid del vehículo impactado) si estás disparando a un jugador que está en un vehículo. Este no se va a llamar como `BULLET_HIT_TYPE_PLAYER` en absoluto.
- Parcialmente arreglado en SA-MP 0.3.7: Si información de armas (weapondata) falsa en eviada por un jugador malicioso, los clientes de otros jugadores pueden congelarse o crashear. Para combatir esto, comprobar si el weaponid reportado es capaz de disparar balas.
:::
## Funciones Relacionadas
- [GetPlayerLastShotVectors](../functions/GetPlayerLastShotVectors): Devuelve el vector del último disparo que efectuó el jugador.
| openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerWeaponShot.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/callbacks/OnPlayerWeaponShot.md",
"repo_id": "openmultiplayer",
"token_count": 1728
} | 368 |
---
title: TextDrawFont
description: Cambia la fuente del texto.
tags: ["textdraw"]
---
## Description
Changes the text font.
| Nombre | Descripcion |
| ------ | ----------- |
| text | El TextDraw a cambiar |
| font | Hay cuatro estilos de fuente, como se muestra a continuación. El valor de fuente 4 especifica que se trata de un sprite txd; 5 especifica que este textdraw puede mostrar modelos de vista previa. Un valor de fuente superior a 5 no se muestra, y cualquier valor superior a 16 crashea el cliente. |
**Estilos disponibles:**

**Fuentes disponibles:**

## Retorno
Esta función no devuelve ningún valor específico.
## Ejemplos
```c
new Text: gMyTextdraw;
public OnGameModeInit()
{
gMyTextdraw = TextDrawCreate(320.0, 425.0, "This is an example textdraw");
TextDrawFont(gMyTextdraw, 2);
return 1;
}
```
## Notas
:::tip
Si quieres cambiar la fuente de un textdraw que ya se muestra, no tienes que volver a crearlo. Simplemente usa TextDrawShowForPlayer/TextDrawShowForAll después de modificar el textdraw y el cambio será visible.
:::
## Funciones relacionadas
- [TextDrawCreate](TextDrawCreate): Crear un textdraw.
- [TextDrawDestroy](TextDrawDestroy): Destruir un textdraw.
- [TextDrawColor](TextDrawColor): Establecer el color de un textdraw.
- [TextDrawBoxColor](TextDrawBoxColor): Establecer el color de la caja de un textdraw.
- [TextDrawBackgroundColor](TextDrawBackgroundColor): Establecer el color de fondo de un textdraw.
- [TextDrawAlignment](TextDrawAlignment): Establecer la alineación de un textdraw.
- [TextDrawLetterSize](TextDrawLetterSize): Definir el tamaño de letra del texto de un textdraw.
- [TextDrawTextSize](TextDrawTextSize): Definir el tamaño de la caja de un textdraw.
- [TextDrawSetOutline](TextDrawSetOutline): Definir si el texto tiene borde.
- [TextDrawSetShadow](TextDrawSetShadow): Definir si tiene sombras un textdraw.
- [TextDrawSetProportional](TextDrawSetProportional): Escalar el espaciado del texto en un textdraw a una relación proporcional.
- [TextDrawUseBox](TextDrawUseBox): Alternar si el textdraw tiene una caja o no.
- [TextDrawSetString](TextDrawSetString): Cambiar el texto de un textdraw existente.
- [TextDrawShowForPlayer](TextDrawShowForPlayer): Mostrar un textdraw a un jugador.
- [TextDrawHideForPlayer](TextDrawHideForPlayer): Esconder un textdraw a un jugador.
- [TextDrawShowForAll](TextDrawShowForAll): Mostrar un textdraw a todos los jugadores.
- [TextDrawHideForAll](TextDrawHideForAll): Esconder un textdraw a todos los jugadores.
| openmultiplayer/web/docs/translations/es/scripting/functions/TextDrawFont.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/es/scripting/functions/TextDrawFont.md",
"repo_id": "openmultiplayer",
"token_count": 894
} | 369 |
---
id: ShowPlayerDialog
title: ShowPlayerDialog
description: یک دیالوگ را در لحظه به بازیکن نشان میدهد
tags: ["player"]
---
<div dir="rtl" style={{ textAlign: "right" }}>
## توضیحات
یک دیالوگ را در لحظه به بازیکن نشان میدهد
| نام | توضیح |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | شناسه بازیکنی که میخواهید دیالوگ برای او نمایش داده شود. |
| dialogid | شناسه دیالوگ جهت پردازش پاسخ بازیکن، 32767 حداکثر مقدار شناسه است، استفاده از شناسه های منفی باعث پنهان شدن هر دیالوگ در حال نمایش میشود. |
| style | [سبک](../resources/dialogstyles.md) دیالوگ |
| caption[] | عنوان دیالوگ که در قسمت بالا نمایش داده میشود. این قسمت نمیتواند بیشتر از 64 حرف باشد در غیر این صورت ادامه عنوان برش میخورد. |
| info[] | متنی که میخواهیم در قسمت اصلی دیالوگ نمایش داده شود. از \n برای رفتن به خط جدید و از \t برای جدول بندی کردن استفاده کنید. |
| button1[] | متن دکمه ای که در سمت چپ قرار میگیرد. |
| button2[] | متن دکمه ای که در سمت راست قرار میگیرد. اگر میخواهید چیزی نمایش داده نشود از ( "" ) استفاده کنید. |
## مقادیر برگشتی
1: تابع با موفقیت اجرا شد
0: اجرای تابع موفق نبود. به این معنا که بازیکن متصل نبود.
## مثال ها
</div>
```c
// Tarif kardane shenase dialog ba estefade az enum:
enum
{
DIALOG_LOGIN,
DIALOG_WELCOME,
DIALOG_WEAPONS
}
// hamchenin mitavanim az #define ham estefade konim:
#define DIALOG_LOGIN 1
#define DIALOG_WELCOME 2
#define DIALOG_WEAPONS 3
//Enums pishnahad mishavad, choon shoma niazi nadarid ke shenase ra bezanid. Ba in hal enum ha az memory estefade mikonand zakhire tarif ha, dar hali ke define ha dar sahne compile 'pre-processor' pardazesh shode and.
// Masalan baraye DIALOG_STYLE_MSGBOX:
ShowPlayerDialog(playerid, DIALOG_WELCOME, DIALOG_STYLE_MSGBOX, "Notice", "You are connected to the server", "Close", "");
// Masalan baraye DIALOG_STYLE_INPUT:
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_INPUT, "Login", "Enter your password below:", "Login", "Cancel");
// Masalan baraye DIALOG_STYLE_LIST:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_LIST, "Weapons", "AK47\nM4\nSniper Rifle", "Option 1", "Option 2");
// Masalan baraye DIALOG_STYLE_PASSWORD:
ShowPlayerDialog(playerid, DIALOG_LOGIN, DIALOG_STYLE_PASSWORD, "Login", "Enter your password below:", "Login", "Cancel");
// Masalan baraye DIALOG_STYLE_TABLIST:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_TABLIST, "Buy Weapon", "Deagle\t$5000\t100\nSawnoff\t$5000\t100\nPistol\t$1000\t50", "Select", "Cancel");
// Masalan baraye DIALOG_STYLE_TABLIST_HEADERS:
ShowPlayerDialog(playerid, DIALOG_WEAPONS, DIALOG_STYLE_TABLIST_HEADERS, "Buy Weapon", "Weapon\tPrice\tAmmo\nDeagle\t$5000\t100\nSawnoff\t$5000\t100\nPistol\t$1000\t50", "Select", "Cancel");
```
<div dir="rtl" style={{ textAlign: "right" }}>
## نکته ها
:::tip
پیشنهاد میشود که از enum یا تعریف کردن(#define) برای تعیین شناسه هر دیالوگ استفاده کنید تا در آینده گیچ نشوید. شما نباید هیچوقت از اعداد برای تعریف شناسه استفاده نکنید - این مورد باعث گیچ شدن شما میشود.
:::
:::tip
استفاده از شناسه دیالوگ -1 باعث بسته شدن تمام دیالوگ های باز روی صفحه بازیکن میشود. برای چند رنگ بودن متن از روش color embedding استفاده کنید
:::
## تابع های مرتبط
</div>
- [TextDrawShowForPlayer](TextDrawShowForPlayer.md)
- [OnDialogResponse](../callbacks/OnDialogResponse.md)
| openmultiplayer/web/docs/translations/fa/scripting/functions/ShowPlayerDialog.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fa/scripting/functions/ShowPlayerDialog.md",
"repo_id": "openmultiplayer",
"token_count": 2671
} | 370 |
---
title: OnFilterScriptExit
description: This callback is called when a filterscript is unloaded. It is only called inside the filterscript which is unloaded.
tags: []
---
## Description
Ang callback na ito ay natatawag kapag ang filterscript ay in-unload sa server.
## Examples
```c
public OnFilterScriptExit()
{
print("\n--------------------------------------");
print(" My filterscript unloaded");
print("--------------------------------------\n");
return 1;
}
```
## Mga Kaugnay na Functions
| openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnFilterScriptExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnFilterScriptExit.md",
"repo_id": "openmultiplayer",
"token_count": 144
} | 371 |
---
title: OnPlayerClickTextDraw
description: This callback is called when a player clicks on a textdraw or cancels the select mode with the Escape key.
tags: ["player", "textdraw"]
---
## Description
Ang callback na ito ay natatawag kapag ang player ay pumindot sa isang textdraw o nag cancel sa select mode gamit ang `ESC` key.
| Name | Description |
| --------- | ----------------------------------------------------------------------------- |
| playerid | The ID of the player that clicked on the textdraw. |
| clickedid | The ID of the clicked textdraw. INVALID_TEXT_DRAW if selection was cancelled. |
| Pangalan | Deskripsyon |
| --------- | ----------------------------------------------------------------------------- |
| playerid | Ang ID ng player na pumindot sa textdraw. |
| clickedid | Ang ID ng textdraw na pinindot ng player. INVALID_TEXT_DRAW kapag cinancel. |
## Returns
Lagi itong natatawag una sa mga filterscript kaya kapag nag return 1 ay ibloblock nito ang ibang script mula sa pagtingin dito.
## Mga Halimbawa
```c
new Text:gTextDraw;
public OnGameModeInit()
{
// Paggawa ng textdraw
gTextDraw = TextDrawCreate(10.000000, 141.000000, "MyTextDraw");
TextDrawTextSize(gTextDraw,60.000000, 20.000000);
TextDrawAlignment(gTextDraw,0);
TextDrawBackgroundColor(gTextDraw,0x000000ff);
TextDrawFont(gTextDraw,1);
TextDrawLetterSize(gTextDraw,0.250000, 1.000000);
TextDrawColor(gTextDraw,0xffffffff);
TextDrawSetProportional(gTextDraw,1);
TextDrawSetShadow(gTextDraw,1);
TextDrawSetSelectable(gTextDraw, 1);
return 1;
}
public OnPlayerKeyStateChange(playerid, KEY:newkeys, KEY:oldkeys)
{
if (newkeys == KEY_SUBMISSION)
{
TextDrawShowForPlayer(playerid, gTextDraw);
SelectTextDraw(playerid, 0xFF4040AA);
}
return 1;
}
public OnPlayerClickTextDraw(playerid, Text:clickedid)
{
if (clickedid == gTextDraw)
{
SendClientMessage(playerid, 0xFFFFFFAA, "You clicked on a textdraw.");
CancelSelectTextDraw(playerid);
return 1;
}
return 0;
}
```
## Mga Dapat Unawain
:::warning
Ang napipindot na area ay na dedefine sa TextDrawTextSize. Ang x at y na parameter ay napapass sa function na iyon at hindi eto pwedeng maging zero o negative. Wag gamitin ang CancelSelectTextdraw ng hindi alam ang gagawin o walang pasubali sa callback. Magreresulta ito sa infinite na loop.
:::
## Related Functions
- [OnPlayerClickPlayerTextDraw](../callbacks/OnPlayerClickPlayerTextDraw.md): Natatawag kapag ang player ay pumindot sa isang player-textdraw.
- [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer.md): Natatawag kapag ang player ay pinindot ang ibang player.
| openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerClickTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/callbacks/OnPlayerClickTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 1124
} | 372 |
---
title: AddPlayerClass
description: Nagdaragdag ng klase sa pagpili ng klase.
tags: ["player"]
---
## Description
Nagdaragdag ng klase sa pagpili ng klase. Ginagamit ang mga klase upang ang mga manlalaro ay maaaring mag-spawn ng balat na kanilang pinili.
| Name | Description |
| ------------- | ------------------------------------------------------------------------------- |
| modelid | Ang balat na kung saan ang player ay pangingitlog sa. |
| Float:spawn_x | Ang X coordinate ng spawnpoint ng klase na ito. |
| Float:spawn_y | Ang Y coordinate ng spawnpoint ng klase na ito. |
| Float:spawn_z | Ang Z coordinate ng spawnpoint ng klase na ito. |
| Float:z_angle | Ang direksyon kung saan dapat harapin ang manlalaro pagkatapos ng pangingitlog. |
| weapon1 | Ang unang spawn-weapon para sa player. |
| weapon1_ammo | Ang dami ng bala para sa pangunahing spawn weapon. |
| weapon2 | Ang pangalawang spawn-weapon para sa player. |
| weapon2_ammo | Ang dami ng bala para sa pangalawang spawn weapon. |
| weapon3 | Ang ikatlong spawn-weapon para sa player. |
| weapon3_ammo | Ang dami ng bala para sa ikatlong spawn weapon. |
## Returns
Ang ID ng klase na kakadagdag lang.
319 kung naabot ang limitasyon ng klase (320). Ang pinakamataas na posibleng class ID ay 319.
## Examples
```c
public OnGameModeInit()
{
// Maaaring mag-spawn ang mga manlalaro gamit ang CJ skin (0) o The Truth skin (1).
AddPlayerClass(0, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // CJ
AddPlayerClass(1, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // The Truth
return 1;
}
```
## Notes
:::tip
Ang maximum class ID ay 319 (simula sa 0, kaya ang kabuuang 320 na klase). Kapag naabot na ang limitasyong ito, papalitan ng anumang klase na idaragdag ang ID 319.
:::
## Related Functions
- [AddPlayerClassEx](AddPlayerClassEx): Magdagdag ng klase na may default na team.
- [SetSpawnInfo](SetSpawnInfo): Itakda ang setting ng spawn para sa isang player.
- [SetPlayerSkin](SetPlayerSkin): Itakda ang balat ng isang manlalaro.
| openmultiplayer/web/docs/translations/fil/scripting/functions/AddPlayerClass.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/AddPlayerClass.md",
"repo_id": "openmultiplayer",
"token_count": 1155
} | 373 |
---
title: AttachCameraToPlayerObject
description: Nag-attach ng camera ng player sa isang player-object.
tags: ["player", "camera"]
---
## Description
Nag-attach ng camera ng player sa isang player-object. Nagagawa ng player na ilipat ang kanyang camera habang nakakabit ito sa isang bagay. Maaaring gamitin sa MovePlayerObject at AttachPlayerObjectToVehicle.
| Name | Description |
| -------------- | ------------------------------------------------------------------------------ |
| playerid | Ang ID ng player kung saan ikakabit ang kanilang camera sa isang player-object.|
| playerobjectid | Ang ID ng player-object kung saan ikakabit ang camera ng player. |
## Returns
Ang function na ito ay hindi nagbabalik ng anumang partikular na halaga.
## Examples
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/attach", false))
{
new playerobject = CreatePlayerObject(playerid, 1245, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0);
AttachCameraToPlayerObject(playerid, playerobject);
SendClientMessage(playerid, 0xFFFFFFAA, "Your camera is now attached to an object.");
return 1;
}
return 0;
}
```
## Notes
:::tip
Ang player-object ay dapat gawin bago subukang ilagay ang camera ng player dito.
:::
## Related Functions
- [AttachCameraToObject](AttachCameraToObject): Kinakabit ang camera ng player sa isang pandaigdigang bagay.
- [SetPlayerCameraPos](SetPlayerCameraPos): I-set ang posisyon ng camera ng player.
- [SetPlayerCameraLookAt](SetPlayerCameraLookAt): I-set kung saan dapat humarap ang camera ng player. | openmultiplayer/web/docs/translations/fil/scripting/functions/AttachCameraToPlayerObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/AttachCameraToPlayerObject.md",
"repo_id": "openmultiplayer",
"token_count": 614
} | 374 |
---
title: EnableZoneNames
description: Binibigyang-daan ng function na ito na i-on ang mga pangalan ng zone / area gaya ng text na "Vinewood" o "Doherty" sa kanang ibaba ng screen habang papasok ang mga ito sa lugar.
tags: []
---
## Description
Binibigyang-daan ng function na ito na i-on ang mga pangalan ng zone / area gaya ng text na "Vinewood" o "Doherty" sa kanang ibaba ng screen habang papasok ang mga ito sa lugar. Isa itong opsyon sa gamemode at dapat itakda sa callback na OnGameModeInit.
| Name | Description |
| ------ | ----------------------------------------------------------------------------------------- |
| enable | Isang toggle na opsyon para sa kung gusto mo o hindi ang mga pangalan ng zone na i-on o i-off. Naka-off ang 0 at naka-on ang 1. |
## Returns
Ang function na ito ay hindi nagbabalik ng anumang value.
## Examples
```c
public OnGameModeInit()
{
EnableZoneNames(1);
return 1;
}
```
## Notes
:::warning
Inalis ang function na ito sa SA-MP 0.3. Ito ay dahil sa mga pag-crash na dulot nito.
::: | openmultiplayer/web/docs/translations/fil/scripting/functions/EnableZoneNames.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/EnableZoneNames.md",
"repo_id": "openmultiplayer",
"token_count": 437
} | 375 |
---
title: PauseRecordingPlayback
description: Ipo-pause nito ang pag-play muli ng recording.
tags: []
---
## Description
Ipo-pause nito ang pag-play muli ng recording.
## Related Functions
- [ResumeRecordingPlayback](../functions/ResumeRecordingPlayback): Ipagpapatuloy ang pagre-record kung naka-pause ito. | openmultiplayer/web/docs/translations/fil/scripting/functions/PauseRecordingPlayback.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/PauseRecordingPlayback.md",
"repo_id": "openmultiplayer",
"token_count": 104
} | 376 |
---
title: SpawnPlayer
description: (Re)Spawns ng isang manlalaro.
tags: ["player"]
---
## Description
(Re)Spawns ng isang manlalaro.
| Name | Description |
| -------- | ------------------------------ |
| playerid | Ang ID ng player na mag i-spawn.|
## Returns
1: Matagumpay na naisakatuparan ang function.
0: Nabigo ang function na isagawa. Nangangahulugan ito na ang manlalaro ay hindi konektado.
## Examples
```c
if (strcmp(cmdtext, "/spawn", true) == 0)
{
SpawnPlayer(playerid);
return 1;
}
```
## Notes
:::tip
Pinapatay ang manlalaro kung sila ay nasa sasakyan at mag i-spawn ng may hawak na bote.
:::
## Related Functions
- [SetSpawnInfo](SetSpawnInfo): I-set ang setting ng spawn para sa isang manlalaro.
- [AddPlayerClass](AddPlayerClass): Maglagay ng class.
- [OnPlayerSpawn](../callbacks/OnPlayerSpawn): Tinatawag kapag nag-spawn ang isang manlalaro. | openmultiplayer/web/docs/translations/fil/scripting/functions/SpawnPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/SpawnPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 342
} | 377 |
---
title: setarg
description: Magtakda ng argument na naipasa sa isang function.
tags: []
---
<LowercaseNote />
## Description
Magtakda ng argument na naipasa sa isang function.
| Name | Description |
| ----- | ----------------------------------------------------------- |
| arg | Ang numero ng pagkakasunud-sunod ng argument. Gamitin ang 0 para sa unang argument. |
| index | Ang index (kung ang argument ay isang array). |
| value | Ang halaga kung saan itatakda ang argument. |
## Returns
[edit]
## Related Functions
- [getarg](getarg): Kumuha ng argument mula sa isang variable na listahan ng argument.
- [numargs](numargs): Ibalik ang bilang ng mga argument. | openmultiplayer/web/docs/translations/fil/scripting/functions/setarg.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fil/scripting/functions/setarg.md",
"repo_id": "openmultiplayer",
"token_count": 283
} | 378 |
---
title: OnDialogResponse
description: Cette callback est appelée lorsqu'un joueur lorsqu'un joueur répond à une boîte de dialogue affichée à l'aide de ShowPlayerDialog en cliquant sur un bouton, en appuyant sur ENTRÉE / ÉCHAP ou en double-cliquant sur un élément de liste (si vous utilisez un `DIALOG_STYLE_LIST`).
tags: [Dialog, DIALOG_STYLE_LIST, OnDialogReponse, listitem, dialogid]
---
## Paramètres
Cette callback est appelée lorsqu'un joueur lorsqu'un joueur répond à une boîte de dialogue affichée à l'aide de ShowPlayerDialog en cliquant sur un bouton, en appuyant sur ENTRÉE / ÉCHAP ou en double-cliquant sur un élément de liste (si vous utilisez un `DIALOG_STYLE_LIST`).
| Nom | Description |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `int` playerid | ID du joueur qui a répondu au dialog |
| `int` dialogid | ID du dialog auquel le joueur répond, assigné dans ShowPlayerDialog |
| `int` response | 1 pour le bouton de gauche, 0 pour celui de droite (s'il n'y a qu'un bouton apparent = toujours 1) |
| `int` listitem | ID de l'item sélectionné par le joueur _(commence à 0, seulement dans les `DIALOG_STYLE_LIST`, pour le reste c'est -1) |
| `string` inputtext[] | Texte inséré dans la boîte de saisie par le joueur, ou le texte de l'élément de l'item sélectionné |
## Valeur de retour
Return 1 à la fin de chaque boîte de dialogue manipulée.
En revanche, return 0 à la fin de la callback.
## Exemple
```c
// Dans un premier temps, définir l'ID du dialog concerné.
#define DIALOG_REGLES 1
// À mettre à la suite d'une commande, par exemple. Dans notre cas, il s'agit d'un style de dialog MSGBOX (n'affiche qu'un message).
ShowPlayerDialog(playerid, DIALOG_REGLES, DIALOG_STYLE_MSGBOX, "Serveur / Règlement", "- Pas de cheat\n- Pas de spam\n- Respect d'autrui\n\nAcceptez-vous ces règles ?", "Oui", "Non !");
public OnDialogResponse(playerid, dialogid, response, listitem, inputtext[])
{
if (dialogid == DIALOG_REGLES)
{
if (response) // Si le joueur a cliqué sur "Oui"
{
SendClientMessage(playerid, COLOR_GREEN, "Merci d'avoir accepté les règles du serveur ! :)");
}
else // Si le joueur a fait ECHAP ou a cliqué sur "Non !"
{
Kick(playerid);
}
return 1; // Nous avons manipulé un dialog, donc return 1. Tout comme dans OnPlayerCommandText.
}
return 0; // Vous DEVEZ faire un return 0! Comme dans OnPlayerCommandText.
}
```
## Notes
:::tip
Les paramètres peuvent changer selon le style de dialog ([voir plus de styles de dialog](../resources/dialogstyles.md)).
:::
:::tip
Il est important d'avoir plusieurs dialogids, surtout si vous en faites plusieurs.
:::
:::warning
Le dialog ouvert par un joueur ne se cache pas quand le serveur redémarre, le serveur va afficher "Warning: PlayerDialogResponse PlayerId: 0 dialog ID doesn't match last sent dialog ID" si un joueur répond à ce dialog après le redémarrage.
:::
## Fonctions connexes
- [ShowPlayerDialog](../functions/ShowPlayerDialog.md): affiche le Dialog à un joueur.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnDialogResponse.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnDialogResponse.md",
"repo_id": "openmultiplayer",
"token_count": 1503
} | 379 |
---
title: OnPlayerEnterVehicle
description: Cette callback est appelée quand un joueur commence à entrer dans un véhicule, c'est-à-dire que le joueur n'est pas encore dans le véhicule quand la callback est appelée.
tags: ["player", "vehicle"]
---
## Paramètres
Cette callback est appelée quand un joueur commence à entrer dans un véhicule, c'est-à-dire que le joueur n'est pas encore dans le véhicule quand la callback est appelée.
| Nom | Description |
| ----------------- | ------------------------------------------------------------ |
| `int` playerid | ID du joueur qui tente d'entrer dans le véhicule |
| `int` vehicleid | ID du véhicule dans lequel le joueur tente d'entrer |
| `int` ispassenger | **0** s'il entre en conducteur. **1** s'il entre en passager |
## Valeur
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 OnPlayerEnterVehicle(playerid, vehicleid, ispassenger)
{
new string[128];
format(string, sizeof(string), "Vous entrez dans le véhicule ID : %i", vehicleid);
SendClientMessage(playerid, 0xFFFFFFFF, string);
return 1;
}
```
## Astuces
:::tip
Cette callback est appelée quand le joueur **COMMENCE** à entrer dans un véhicule, pas quand il effectivement dedans _(v. [OnPlayerStateChange](OnPlayerStateChange))_.
OnPlayerEnterVehicle est quand même appelé si le joueur est interdit d'entrer dans le véhicule _(par exemple si celui-ci est verrouillé)_.
:::
## Fonctions connexes
- [PutPlayerInVehicle](../functions/PutPlayerInVehicle): Met un joueur dans le véhicule.
- [GetPlayerVehicleSeat](../functions/GetPlayerVehicleSeat): Vérifie la place du joueur dans le véhicule.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerEnterVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerEnterVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 755
} | 380 |
---
title: OnPlayerRequestDownload
description: Cette callback est appelée quand un joueur sollicite le téléchargement des custom models.
tags: ["player"]
---
<VersionWarn name='callback' version='SA-MP 0.3.DL R1' />
## Paramètres
Cette callback est appelée quand un joueur sollicite le téléchargement des custom models.
| Nom | Description |
| -------------- | ----------------------------------------------------------------------------------------------------------------- |
| `int` playerid | ID du joueur qui sollicite le téléchargement de custom models ID of the player that request custom model download |
| `int` type | Type de requête (voir _infra_) |
| `int` crc | Numéro CRC du fichier custom |
## Valeur de retour
**1** - Accepte la requête de téléchargement
**0** - Refuse la requête de téléchargement
## Exemple
```c
#define DOWNLOAD_REQUEST_EMPTY (0)
#define DOWNLOAD_REQUEST_MODEL_FILE (1)
#define DOWNLOAD_REQUEST_TEXTURE_FILE (2)
new baseurl[] = "https://files.open-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;
}
```
## Callback connexe
- [OnPlayerFinishedDownloading](OnPlayerFinishedDownloading): Appelée lorsqu'un joueur fini le téléchargement.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerRequestDownload.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnPlayerRequestDownload.md",
"repo_id": "openmultiplayer",
"token_count": 917
} | 381 |
---
title: OnTrailerUpdate
description: Cette callback est appelée quand un joueur envoie une mise à jour d'un trailer (véhicule).
tags: []
---
## Paramètres
Cette callback est appelée quand un joueur envoie une mise à jour d'un trailer (véhicule).
| Name | Description |
| ---------------- | ---------------------------------------- |
| `int` playerid | L'ID du joueur qui envoie la mise à jour |
| `int` vehicleid | Le Trailer mis à jour |
## Valeur de retour
**0** - Annule l'envoi de toutes les mises à jour de Trailer à d'autres joueurs. La mise à jour est toujours envoyée au joueur qui met à jour.
**1** - Traite la mise à jour ddu Trailer comme d'habitude et la synchronise entre tous les joueurs.
## Exemple
```c
public OnTrailerUpdate(playerid, vehicleid)
{
DetachTrailerFromVehicle(GetPlayerVehicleID(playerid));
return 0;
}
```
## Astuces
:::warning
Cette callback est appelée très fréquemment par seconde et par Trailer. Vous devez vous abstenir d'implémenter des calculs intensifs ou des opérations d'écriture / lecture de fichiers intensives dans cette callback.
:::
## Fonctions connexes
- [GetVehicleTrailer](../functions/GetVehicleTrailer): Vérifie quel Trailer le véhicule pousse.
- [IsTrailerAttachedToVehicle](../functions/IsTrailerAttachedToVehicle): Vérifie si un Trailer est attaché à un véhicule.
- [AttachTrailerToVehicle](../functions/AttachTrailerToVehicle): Attache un Trailer à un véhicule.
- [DetachTrailerFromVehicle](../functions/DetachTrailerFromVehicle): Détache le Trailer d'un véhicule.
| openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnTrailerUpdate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/scripting/Callbacks/OnTrailerUpdate.md",
"repo_id": "openmultiplayer",
"token_count": 606
} | 382 |
---
title : Problèmes courants
---
## Le serveur plante instantanément au démarrage
Le plus souvent, il s'agit d'une erreur dans votre fichier server.cfg ou de votre mode de jeu manquant. Vérifiez le fichier server_log.txt et la raison doit être située en bas. Sinon, vérifiez le fichier crashinfo.txt. La meilleure solution pour savoir ce qui cause le crash est d'utiliser le plugin de détection de crash de Zeex/0x5A656578 ([cliquez pour le lien](https://github.com/Zeex/samp-plugin-crashdetect)) qui donnera plus d'informations comme les numéros de ligne, les noms de fonction, les valeurs de paramètre, etc. Si le script est compilé en mode débogage (indicateur -d3) pour que le compilateur mette des informations supplémentaires sur tout cela dans la sortie .amx.
## Le serveur ne fonctionne pas - le pare-feu est désactivé
Vous devrez rediriger vos ports pour permettre aux joueurs de rejoindre votre serveur. Vous pouvez rediriger vos ports à l'aide du vérificateur de ports PF. Téléchargez-le sur : www.portforward.com Si les ports ne sont pas redirigés, cela signifie que vous devez les ouvrir dans votre routeur. Vous pouvez consulter la liste des routeurs sur [http://portforward.com/english/routers/port_forwarding/routerindex.htm](http://portforward.com/english/routers/port_forwarding/routerindex.htm "http://portforward .com/english/routers/port_forwarding/routerindex.htm")
Il contient toutes les informations sur la façon de transférer les ports.
## 'Le paquet a été modifié'
L'erreur généralement affichée comme:
```
[hh:mm:ss] Le paquet a été modifié, envoyé par id : <id>, ip : <ip> :<port>
```
se produit lorsqu'un joueur expire ou rencontre actuellement des problèmes de connexion.
## 'Attention : le client a dépassé la limite de messages'
L'erreur généralement affichée comme:
```
Avertissement : le client a dépassé 'messageslimit' (1) <ip> :<port> (<count>) Limite : x/sec
```
se produit lorsque le nombre de messages par seconde qu'un client envoie au serveur dépasse.
## 'Attention : le client a dépassé la limite d'accusé de réception'
L'erreur généralement affichée comme :
```
Avertissement : le client a dépassé 'ackslimit' <ip>:<port> (<count>) Limite : x/sec
```
se produit lorsque la limite d'accusé de réception dépasse.
## 'Attention : le client a dépassé la limite de trous de messages'
L'erreur généralement affichée comme :
```
Avertissement : le client a dépassé 'messageholelimit' (<type>) <ip> :<port> (<count>) Limite : x
```
se produit lorsque la limite de trou de message dépasse.
## 'Attention : trop de messages en panne'
L'erreur généralement affichée comme:
```
Avertissement : Trop de messages dans le désordre du joueur <ip> :<port> (<count>) Limite : x (messageholelimit)
```
Se produit lorsque les "messages hors service" réutilisent le paramètre messageholelimit.
Pour plus d'informations à ce sujet, consultez [ceci](https://open.mp/docs/server/ControllingServer#RCON_Commands)
## Les joueurs obtiennent constamment l'erreur "Unacceptable NickName" mais elle est valide
Si vous êtes sûr d'utiliser un nom acceptable et que le serveur fonctionne sous Windows, essayez de changer l'option de compatibilité de samp-server.exe en Windows 98 et cela devrait être corrigé après un redémarrage du serveur.
Les serveurs Windows avec un temps de disponibilité élevé peuvent également provoquer ce problème. Cela a été remarqué d'environ 50 jours de temps de disponibilité du serveur. Pour le résoudre, un redémarrage est nécessaire.
## `MSVCR___.dll`/`MSVCP___.dll` introuvable
Ce problème se produit régulièrement sur les serveurs Windows lorsque vous essayez de charger un plug-in qui a été développé à l'aide d'une version supérieure du runtime Visual C++ à celle actuellement installée sur votre ordinateur. Pour résoudre ce problème, téléchargez les bibliothèques d'exécution Microsoft Visual C++ appropriées. Notez que le serveur SA-MP est 32 bits, vous devrez donc également télécharger la version 32 bits (x86) du runtime, quelle que soit l'architecture. La version du runtime dont vous avez spécifiquement besoin est indiquée par les numéros dans le nom de fichier (voir le tableau ci-dessous), bien que cela ne fasse pas de mal de les installer tous. Ces bibliothèques ne s'empilent pas, ou en d'autres termes : vous n'obtiendrez pas les runtimes pour les versions 2013 et antérieures si vous installez uniquement la version 2015.
| Numéro de version | Durée d'exécution |
| -------------- | --------------------------------------------- |
| 10.0 | Redistribuable Microsoft Visual C++ 2010 x86 |
| 11.0 | Redistribuable Microsoft Visual C++ 2012 x86 |
| 12.0 | Redistribuable Microsoft Visual C++ 2013 x86 |
| 14.0 | Redistribuable Microsoft Visual C++ 2015 x86 |
| openmultiplayer/web/docs/translations/fr/server/CommonServerIssues.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/fr/server/CommonServerIssues.md",
"repo_id": "openmultiplayer",
"token_count": 1695
} | 383 |
---
title: Masalah Umum
---
## Konten
## Klien
### Saya mendapatkan error "San Andreas cannot be found"
San Andreas Multi-player **bukan** program stand-alone! Program ini menambahkan fungsi multi-player ke San Andreas, dan maka dari itu Anda membutuhkan GTA San Andreas untuk PC - membutuhkan versi **EU/US v1.0**, versi lain, seperti v2.0 atau Steam dan Direct2Drive tidak akan bekerja [Klik di sini untuk mengunduh sebuah patch untuk downgrade GTA:SA Anda ke versi 1.0](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661)
### Saya tidak bisa lihat server apapun di penjelajah SA-MP
Pertama, pastikan Anda telah mengikuti prosedur di [Panduan cepat](https://team.sa-mp.com/wiki/Getting_Started). Jika Anda telah mengikut instruksinya dan tidak bisa melihat server apapun, Anda harus mengijinkan akses SA-MP melalui firewall Anda. Sayangnya, dikarenakan besarnya jumlah aplikasi firewall yang tersedia, kami tidak bisa menawarkan bantuan lebih lanjut - kami sarankan untuk mengunjungi situs jaringan manufaktur atau coba melakukan pencarian di Google. Dan juga pastikan Anda telah menggunakan versi SA:MP terbaru.
### Hanya memuat Single Player, bukan memuat SA-MP
:::warning
Anda seharusnya tidak melihat opsi single player (new game, load game, dll.) - SA-MP seharusnya memuat program ini dan tidak menampilkan opsi ini. Jika Anda melihat "new game" single player termuat, bukan San Andreas Multiplayer.
:::
Single player bisa dimuat dengan 2 alasan - Anda memasang SA:MP ke folder yang salah atau Anda memiliki versi San Andreas yang salah. Jika Anda memiliki versi yang salah, ini mudah untuk diperbaiki. Klik [di sini](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661) untuk mengunduh downgrade patch.
Terkadang menu single-player akan muncul, namun SA:MP akan dimuat dengan baik. Untuk memperbaiki ini, Anda cukup memilih item di menu, lalu tekan ESC hingga keluar, kemudian SA:MP akan termuat.
### Saya mendapatkan pesan "Unacceptable NickName" ketika sedang menghubungi server
Pastikan Anda tidak menggunakan karakter yang tidak diperboleh di nama Anda (hanya gunakan 0-9, a-z, \[\], (), \$, @, ., \_, dan =), dan nama Anda panjangnya tidak lebih dari 20 karakter. Ini juga bisa terjadi ketika pemain berada di server dengan nama yang sama dengan Anda (yang di mana dapat terjadi jika Anda masuk kembali ke server lebih awal setelah timeout atau crash). Dan juga server Windows menjalankan SA-MP dengan uptime lebih dari 50 hari bug ini dapat terjadi.
### Menyangkut di "Connecting to ip:port..."
Server bisa jadi sedang offline, atau Anda tidak dapat terhubung ke server, matikan firewall Anda dan periksa kembali. Jika tetap tidak bisa, Anda harus mengatur firewall Anda dengan baik - jelajahi situr jaringannya dan cari tau caranya. Hal ini dapat terjadi di versi lawas SA-MP, unduh versi terbaru dari [halaman unduh SA-MP](http://sa-mp.com/download.php).
### Saya memiliki GTA San Andreas yang telah dimodifikasi dan SA:MP tidak mau termuat
Jika tidak termuat, maka hapus modifikasi Anda.
### Ketika menjalankan GTA dengan SA:MP, tidak termuat dengan baik
Hapus file gta_sa.set dari folder userfiles dan pastikan Anda tidak memiliki cheat atau modifikasi.
### Game crash ketika sebuah kendaraan meledak
Jika Anda memiliki 2 monitor, maka ada 3 cara untuk menyelesaikan permasalahan ini:
1. Matikan 2dr monitor Anda ketika memainkan SA-MP. (Mungkin Anda tidak terlalu cerdas jika Anda ingin monitornya menyala.)
2. Atur kualitas Visual FX Anda ke low (ESC > Options > Display Setup > Advanced)
3. Ubah folder GTA San Andreas Anda (contoh: menjadi "GTA San Andreas2") (Cara ini selalu bekerja, bagaimanapun kadang cara ini tidak bekerja lagi, jadi Anda harus mengubahnya menjadi nama yang lain.)
### Mouse saya tidak bekerja setelah keluar dari menu pause
Jika mouse Anda tidak bisa bergerak di dalam game dan bekerja sebagian di menu pause, maka Anda seharusnya mematikan opsi multicore [sa-mp.cfg](../../../client/ClientCommands#file-sa-mpcfg "Sa-mp.cfg") (atur menjadi 0). Menekan Escape secara terus-menerus hingga mouse bergerak mungkin bisa dengan cara ini, namun ini bukan solusi yang cerdik.
### File dinput8.dll menghilang
Ini kemungkinan terjadi ketika DirectX tidak terpasang dengan baik, cobalah pasang ulang kembali - jangan lupa untuk menyalakan ulang PC Anda. Jika masalah masih terjadi, buka folder C:\\Windows\\System32 dan salin file dinput.dll ke direktori utama GTA San Andreas Anda. Cara ini akan menyelesaikan masalah Anda.
### Saya tidak bisa melihat nametag pemain
Mohon lebih hati-hati karena beberapa server mungkin mematikan nametag secara keseluruhan. Selain itu, masalah ini sering terjadi di komputer dengan prosesor Intel HD integrated graphics (yang di mana tidak ditujukan untuk gaming). Sayangnya, hingga saat ini, permasalahan utamanya masih belum diketahui dan tidak ada perbaikan secara universal yang tersedia. Perbaikan jangka panjangnya adalah pasang kartu grafis dedikasi di komputer Anda, jika hal ini memungkinkan dan bujet Anda menginjinkannya.
| openmultiplayer/web/docs/translations/id/client/CommonClientIssues.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/client/CommonClientIssues.md",
"repo_id": "openmultiplayer",
"token_count": 1860
} | 384 |
---
title: OnObjectMoved
description: Callback ini akan terpanggil ketika sebuah object berpindah setelah MoveObject (ketika selesai bergerak).
tags: []
---
## Deskripsi
Callback ini akan terpanggil ketika sebuah object berpindah setelah MoveObject (ketika selesai bergerak).
| Nama | Deskripsi |
| -------- | -------------------------------------- |
| objectid | ID dari sebuah object yang dipindahkan |
## Returns
Ini akan selalu terpanggil pertama di filterscripts.
## Contoh
```c
public OnObjectMoved(objectid)
{
printf("Object %d telah selesai bergerak", objectid);
return 1;
}
```
## Catatan
:::tip
SetObjectPos tidak akan bekerja ketika menggunakan callback ini. Untuk memperbaiki, buatlah ulang objectnya.
:::
## Fungsi Terkait
- [MoveObject](../functions/MoveObject.md): Memindahkan Object.
- [MovePlayerObject](../functions/MovePlayerObject.md): Memindahkan player object.
- [IsObjectMoving](../functions/IsObjectMoving.md): Mengecek apakah object sedang bergerak.
- [StopObject](../functions/StopObject.md): Menghentikan object yang bergerak.
- [OnPlayerObjectMoved](OnPlayerObjectMoved.md): Terpanggil ketika player object berhenti bergerak.
| openmultiplayer/web/docs/translations/id/scripting/callbacks/OnObjectMoved.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnObjectMoved.md",
"repo_id": "openmultiplayer",
"token_count": 442
} | 385 |
---
title: OnPlayerRequestClass
description: Callback ini akan terpanggil ketika seorang pemain mengubah kelas pada pemilihan kelas (dan saat pemilihan kelas pertama kali muncul).
tags: ["player"]
---
## Deskripsi
Callback ini akan terpanggil ketika seorang pemain mengubah kelas pada pemilihan kelas (dan saat pemilihan kelas pertama kali muncul).
| Nama | Deskripsi |
| -------- | ------------------------------------------------------------------ |
| playerid | ID pemain yang mengubah kelas |
| classid | ID kelas yang saat ini dilihat (dikembalikan oleh AddPlayerClass). |
## Returns
Selalu terpanggil pertama di filterscript.
## Contoh
```c
public OnPlayerRequestClass(playerid,classid)
{
if (classid == 3 && !IsPlayerAdmin(playerid))
{
SendClientMessage(playerid, COLOR_RED, "This skin is only for admins!");
return 0;
}
return 1;
}
```
## Catatan
:::tip
Callback ini juga dipanggil ketika pemain menekan tombol F4.
:::
## Fungsi Terkait
- [AddPlayerClass](../functions/AddPlayerClass): Menambahkan kelas
| openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerRequestClass.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/callbacks/OnPlayerRequestClass.md",
"repo_id": "openmultiplayer",
"token_count": 486
} | 386 |
---
title: CreatePickup
description: Fungsi ini melakukan hal yang sama persis seperti AddStaticPickup, kecuali ia mengembalikan ID pengambilan yang dapat digunakan untuk menghancurkannya setelah itu dan dilacak menggunakan OnPlayerPickUpPickup.
tags: []
---
## Deskripsi
Fungsi ini melakukan sama persis dengan AddStaticPickup, kecuali ia mengembalikan ID pengembalian yang dapat digunakan untuk menghancurkannya setelah itu dilacak menggunakan OnPlayerPickUpPickup.
| Nama | Deskripsi |
| ----------------------------------- | --------------------------------------------------------------------------------- |
| [model](../resources/pickupids) | Model dari pickup |
| [type](../resources/pickuptypes) | Tipe pickup. Menentukan bagaimana pickup merespon saat diambil. |
| Float:X | Membuat pickup di kordinat X. |
| Float:Y | Membuat pickup di kordinat Y. |
| Float:Z | Membuat pickup di kordinat Y |
| virtualworld | Virtual World dari pickup. Gunakan -1 untuk membuat pickup di seluruh Virtual World |
## Returns
ID pickup yang dibuat, -1 saat gagal (batas maksimum pengambilan).
## Contoh
```c
new pickup; // Membuat variable untuk menyimpan pickup ID
public OnGameModeInit()
{
pickup = CreatePickup(1242, 2, 1503.3359, 1432.3585, 10.1191, -1);
// Membuat pickup armor dan menyimpan di ID 'pickup'
return 1;
}
// Later..
DestroyPickup(pickup); // Contoh penggunaan dari pickup ID.
pickup = 0; // Variable pickup perlu diatur ulang untuk menghindari konflik kedepannya.
```
## Catatan
:::tip
Satu-satunya pickup yang dapat diambil dari dalam kendaraan adalah 14 (kecuali pickup khusus seperti suap). Pickups ditunjukan, dan dapat diambil oleh semua pemain. Ada kemungkinan jika DestroyPickup() digunakan saat pickup diambil, lebih dari satu pemain dapat mengambil pickup, karena lag. Ini dapat dielakan melalui penggunaan variabel. Jenis pickup tertentu datang dengan 'respons otomatis', misalnya menggunakan model M4 di pickup akan secara otomatis memberikan pemain senjata dan beberapa amunisi. Untuk pickup yang sepenuhnya scripted, tipe 1 harus digunakan.
:::
:::peringatan
Bug yang diketahui: Pickups yang mempunyai X atau Y kurang dari -4096.0 atau lebih besar dari 4096.0 tidak akan muncul dan tidak akan memicu OnPlayerPickUpPickup salah satu.
:::
## Fungsi Terkait
- [AddStaticPickup](AddStaticPickup): Menambahkan Static Pickup.
- [DestroyPickup](DestroyPickup): Menghancurkan Pickup.
- [OnPlayerPickUpPickup](../callbacks/OnPlayerPickUpPickup): Memanggil ketika pemain mengambil pickup. | openmultiplayer/web/docs/translations/id/scripting/functions/CreatePickup.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/CreatePickup.md",
"repo_id": "openmultiplayer",
"token_count": 1311
} | 387 |
---
title: strcmp
description: Fungsi ini membandingkan kedua string untuk mengecek apakah mereka sama.
tags: ["string"]
---
<LowercaseNote />
## Deskripsi
Fungsi ini membandingkan kedua string untuk mengecek apakah mereka sama.
| Nama | Deskripsi |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| string1 | String pertama yang akan di bandingkan. |
| string2 | String kedua yang akan di bandingkan. |
| ignorecase (opsional) | Saat di set true, besar/kecil huruf tidak mempengaruhi - HeLLo sama dengan Hello. Saat di set false, mereka berbeda. |
| length (opsional) | Saat panjang nya di set, karakter pertama x akan di bandingkan - "Hello" dan "Hell No" dengan panjang nya 4 akan melaporkan string nya sama. |
## Returns
0 jika stringnya sama dengan lainnya pada panjang tertentu;1 atau -1 jika sebuah karakter tidak sama: string1[i] - string2[i] ('i' mewakili indeks karakter dimulai dari 0);perbedaan jumlah karakter jika satu string cocok dengan bagian dari string lain.
## Contoh
```c
new string1[] = "Hello World";
new string2[] = "Hello World";
// Cek apakah string nya sama
if (!strcmp(string1, string2))
new string3[] = "Hell";
// Cek apakah 4 karakter string awal sama
if (!strcmp(string2, string3, false, 4))
// Cek string kosong dengan isnull()
if (!strcmp(string1, string2) && !isnull(string1) && !isnull(string2))
// Definisi dari isnull():
#if !defined isnull
#define isnull(%1) ((!(%1[0])) || (((%1[0]) == '\1') && (!(%1[1]))))
#endif
```
## Catatan
:::warning
Fungsi ini me-return 0 jika stringnya kosong. Cek string kosong dengan isnull(). Jika anda bandingkan strings dari sebuah file teks, anda harus mempertimbangkan karakter khusus seperti 'carriage return' dan 'new line' (\r \n), seperti yang telah disertakan, saat menggunakan fread.
:::
## Fungsi Terkait
- [strfind](strfind): Mencari sebuah string di string lainnya.
- [strdel](strdel): Menghapus bagian dari sebuah string.
- [strins](strins): Memasukkan teks kedalam sebuah string.
- [strlen](strlen): Mendapatkan panjang dari sebuah string.
- [strmid](strmid): Mengekstrak bagian dari sebuah string ke string lainnya.
- [strpack](strpack): Membungkus sebuah string menjadi string baru.
- [strval](strval): Mengkonversi sebuah string menjadi integer.
- [strcat](strcat): Menggabungkan dua buah string menjadi sebuah string.
- http://www.compuphase.com/pawn/String_Manipulation.pdf
| openmultiplayer/web/docs/translations/id/scripting/functions/strcmp.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/functions/strcmp.md",
"repo_id": "openmultiplayer",
"token_count": 1322
} | 388 |
---
id: markermodes
title: Mode Penanda
---
Ini digunakan dengan [ShowPlayerMarkers](../functions/ShowPlayerMarkers).
```c
PLAYER_MARKERS_MODE_OFF (0)
PLAYER_MARKERS_MODE_GLOBAL (1)
PLAYER_MARKERS_MODE_STREAMED (2)
```
| openmultiplayer/web/docs/translations/id/scripting/resources/markermodes.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/resources/markermodes.md",
"repo_id": "openmultiplayer",
"token_count": 108
} | 389 |
---
id: weaponskills
title: Keterampilan Senjata
description: Nilai kemampuan senjata yang untuk digunakan dengan SetPlayerSkillLevel.
---
## Deskripsi
Daftar kemampuan senjata yang digunakan untuk menetapkan tingkat kemampuannya player menggunakan fungsi [SetPlayerSkillLevel](../functions/SetPlayerSkillLevel.md).
## Tingkat Keterampilan
```c
0 - WEAPONSKILL_PISTOL
1 - WEAPONSKILL_PISTOL_SILENCED
2 - WEAPONSKILL_DESERT_EAGLE
3 - WEAPONSKILL_SHOTGUN
4 - WEAPONSKILL_SAWNOFF_SHOTGUN
5 - WEAPONSKILL_SPAS12_SHOTGUN
6 - WEAPONSKILL_MICRO_UZI
7 - WEAPONSKILL_MP5
8 - WEAPONSKILL_AK47
9 - WEAPONSKILL_M4
10 - WEAPONSKILL_SNIPERRIFLE
```
| openmultiplayer/web/docs/translations/id/scripting/resources/weaponskills.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/id/scripting/resources/weaponskills.md",
"repo_id": "openmultiplayer",
"token_count": 284
} | 390 |
---
title: Przyczyń się do rozwoju
description: Jak wnieść swój wkład do SA-MP Wiki i dokumentacji open.mp.
---
Kod źródłowy tej dokumentacji jest dostępny dla każdego, kto chce wnieść jakiekolwiek zmiany! Wszystko czego potrzebujesz to konto na [GitHubie](https://github.com) i trochę wolnego czasu. Nie musisz znać obsługi systemu Git, wszystko możesz zrobić przez wersję przeglądarkową!
Jeżeli chcesz zaopiekować się konkretnym językiem, otwórz PR do pliku [`CODEOWNERS`](https://github.com/openmultiplayer/web/blob/master/CODEOWNERS) i dodaj linię dla katalogu Twojego języka wraz ze swoją nazwą użytkownika.
## Edycja treści
Na każdej stronie widoczny jest przycisk, który przenosi Cię do jej edycji na GitHubie:

Na przykład, kliknięcie go na [SetVehicleAngularVelocity](../scripting/functions/SetVehicleAngularVelocity) przeniesie Cię do [tej strony](https://github.com/openmultiplayer/web/edit/master/docs/scripting/functions/SetVehicleAngularVelocity.md), na której dostępny jest edytor tekstowy umożliwiający wprowadzenie zmian do pliku (zakładając, że jesteś zalogowany do GitHuba).
Wprowadź swoje zmiany i wyślij „Pull Request”, który umożliwi opiekunom Wiki oraz innym członkom społeczności na przegląd Twoich zmian, dyskusję na temat ewentualnych dodatkowych zmian, a ostatecznie ich wdrożenie.
## Dodawanie nowej zawartości
Dodawanie nowej zawartości jest nieco bardziej zawiłe. Możesz to zrobić na dwa sposoby:
### Interfejs GitHub
Gdy przeglądasz katalog na GitHubie, w prawym górnym rogu listy plików widoczny jest przycisk „Add file”:

Możesz wgrać wcześniej napisany plik języka Markdown lub napisać go bezpośrednio w edytorze tekstowym GitHuba.
Plik _musi_ mieć rozszerzenie `.md` i zawierać Markdown. Po więcej informacji na temat języka Markdown, sprawdź [ten poradnik](https://guides.github.com/features/mastering-markdown/)
Kiedy skończysz, kliknij „Propose new file” – Pull Request zostanie otwarty do przeglądu.
### Git
Jeżeli chcesz użyć systemu Git, wystarczy sklonować repozytorium Wiki komendą:
```sh
git clone https://github.com/openmultiplayer/wiki.git
```
Otwórz je w swoim ulubionym edytorze. Polecamy Visual Studio Code, ponieważ posiada on świetne narzędzia do edycji i formatowania plików Markdown. Jak możesz zobaczyć, ten plik został napisany przy użyciu Visual Studio Code!

Polecamy także dwie wtyczki, aby uprzyjemnić pracę:
- [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint) autorstwa Davida Ansona - ta wtyczka upewnia się, że Twój Markdown jest sformatowany prawidłowo, poprzez zapobieganie składniowym i semantycznym pomyłkom. Nie wszystkie ostrzeżenia są ważne, ale część z nich może pomóc w poprawieniu czytelności. Jeżeli masz jakieś wątpliwości, po prostu zapytaj opiekunów!
- [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) autorstwa zespołu Prettier.js - ta wtyczka będzie automatycznie formatować Twoje pliki Markdown, aby wszystkie utrzymywały jednolitego stylu. Repozytorium Wiki ma kilka ustawień w `package.json`, z których wtyczka powinna skorzystać automatycznie. Upewnij się, że w ustawieniach swojego edytora masz włączoną opcję „Format On Save” – dzięki temu Twoje pliki Markdown będą automatycznie formatowane przy każdym zapisie!
## Uwagi, wskazówki i konwencje
### Linki wewnętrzne
Nie używaj absolutnych URL-ów do wewnętrznych linków. Używaj relatywnych ścieżek.
- ❌
```md
Do użycia z [OnPlayerClickPlayer](https://www.open.mp/docs/translations/pl/scripting/callbacks/OnPlayerClickPlayer)
```
- ✔
```md
Do użycia z [OnPlayerClickPlayer](../callbacks/OnPlayerClickPlayer)
```
`../` oznacza „przejdź katalog wyżej”, więc jeżeli plik, który edytujesz, znajduje się w katalogu `functions` i linkujesz do `callbacks`, użyj `../`, aby przejść do `scripting/`, a następnie `callbacks/`, aby dostać się do katalogu callbacks. Na końcu podaj nazwę pliku (bez `.md`) callbacka, do którego linkujesz.
### Obrazy
Obrazy trafiają do podkatalogu wewnątrz `/static/images`. Gdy chcesz go wstawić na stronę w `![]()`, używaj po prostu `/images/` jako podstawową ścieżkę (`static` jest tu zbędne, gdyż jest używane tylko w repozytorium).
Jeżeli masz wątpliwości, zajrzyj na inną stronę korzystającą z obrazów i skopiuj kod dowolnego obrazu.
### Metadane
Pierwszą rzeczą w _każdym_ dokumencie tutaj powinny być metadane:
```mdx
---
title: Moja dokumentacja
description: To jest strona o różnych rzeczach oraz burgerach, hura!
---
```
Każda strona powinna posiadać tytuł i opis.
Po pełną listę rzeczy, które mogą trafić pomiędzy `---`, sprawdź [dokumentację Docusaurusa](https://v2.docusaurus.io/docs/markdown-features#markdown-headers).
### Nagłówki
Nie twórz nagłówka poziomu 1 (`<h1>`) używając `#`, ponieważ jest on generowany automatycznie. Twoim pierwszym nagłówkiem _zawsze_ powinien być `##`.
- ❌
```md
# Mój tytuł
To jest dokumentacja dla...
# Podrozdział
```
- ✔
```md
To jest dokumentacja dla...
## Podrozdział
```
### Używaj fragmentów `kodu` dla odniesień technicznych
Gdy piszesz tekst zawierający nazwy funkcji, liczby, wyrażenia czy cokolwiek co nie zalicza się do standardowego, pisanego języka, otocz je \`grawisami\`. Ułatwia to rozdzielenie języka opisowego od odniesień do elementów technicznych takich jak nazwy funkcji czy fragmenty kodu.
- ❌
> Funkcja fopen zawsze zwraca wartość z tagiem File:, nie ma żadnego problemu w tej linii, ponieważ zwracana wartość jest przechowywana w zmiennej również z tagiem File: (należy pamiętać o takiej samej wielkości znaków). Natomiast w następnej linii wartość 4 jest dodana do tej samej zmiennej, a wartość 4 nie posiada żadnego tagu.
- ✔
> Funkcja `fopen` zawsze zwraca wartość z tagiem `File:`, nie ma żadnego problemu w tej linii, ponieważ zwracana wartość jest przechowywana w zmiennej również z tagiem `File:` (należy pamiętać o takiej samej wielkości znaków). Natomiast w następnej linii wartość `4` jest dodana do tej samej zmiennej, a wartość `4` nie posiada żadnego tagu.
W powyższym przykładzie, `fopen` to nazwa funkcji, a nie polskie słowo, dlatego otoczenie go tagiem `kodu` ułatwia rozróżnienie go od pozostałej zawartości.
Dodatkowo, jeżeli tekst odnosi się do dłuższego fragmentu przykładowego kodu, ułatwia to powiązanie wyrazów z przykładem.
### Tabele
Jeżeli tabela ma nagłówki, trafiają one do jej górnej części:
- ❌
```md
| | |
| ------- | ---------------------------------------- |
| Życie | Status silnika |
| 650 | Niezniszczony |
| 650-550 | Biały dym |
| 550-390 | Szary dym |
| 390-250 | Czarny dym |
| < 250 | Płonie (eksploduje kilka sekund później) |
```
- ✔
```md
| Życie | Status silnika |
| ------- | ---------------------------------------- |
| 650 | Niezniszczony |
| 650-550 | Biały dym |
| 550-390 | Szary dym |
| 390-250 | Czarny dym |
| < 250 | Płonie (eksploduje kilka sekund później) |
```
## Migracja z SA-MP Wiki
Większość zawartości została przeniesiona, ale jeśli znajdziesz brakującą stronę, skorzystaj z prostego poradnika konwersji zawartości na Markdown.
### Zdobycie kodu HTML
1. Kliknij ten przycisk
(Firefox)

(Chrome)

2. Najeżdżaj na górną lewą część podstrony, na lewy margines lub na róg, aż zobaczysz `#content`

Lub wyszukaj `<div id=content>`

3. Skopiuj cały kod HTML znajdujący się wewnątrz tego elementu

Teraz masz _tylko_ kod HTML konkretnej _zawartości_ strony, czyli to co nas interesuje i co możesz przekonwertować na Markdown.
### Konwersja HTML na Markdown
Do konwersji podstawowego kodu HTML (bez tabel) na Markdown, użyj:
https://domchristie.github.io/turndown/

^^ Zwróć uwagę, że tabela całkowicie się zepsuła...
### Konwersja tabel HTML na tabele Markdown
Ponieważ powyższe narzędzie nie wspiera tabel, skorzystaj z tego narzędzia:
https://jmalarcon.github.io/markdowntables/
I skopiuj sam element `<table>` do:

### Porządkowanie
Konwersja prawdopodobnie nie będzie perfekcyjna, więc musisz częściowo uporządkować to samemu. Wtyczki formatujące wypisane wyżej powinny w tym pomóc, ale wciąż będzie trzeba spędzić trochę czasu poprawiając pozostałości ręcznie.
Jeżeli nie masz czasu, nie przejmuj się! Wyślij nieskończoną wersję roboczą, a ktoś inny ją dokończy.
## Umowa licencyjna
Wszystkie projekty open.mp posiadają [umowę licencyjną współtwórcy](https://cla-assistant.io/openmultiplayer/homepage). To w zasadzie oznacza, że zgadzasz się na wykorzystanie przez nas Twojej pracy i umieszczenie jej pod licencją open-source. Gdy stworzysz swój pierwszy Pull Request, bot CLA-Assistant zamieści link, w którym możesz potwierdzić swoją zgodę.
| openmultiplayer/web/docs/translations/pl/meta/Contributing.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pl/meta/Contributing.md",
"repo_id": "openmultiplayer",
"token_count": 4877
} | 391 |
---
title: Attach3DTextLabelToPlayer
description: Przyczepia tekst 3D do gracza.
tags: ["player", "3dtextlabel"]
---
## Opis
Przyczepia tekst 3D do gracza.
| Nazwa | Opis |
| --------- | ---------------------------------------------------------------- |
| Text3D:textid | ID tekstu 3D do przyczepienia. Zwracane przez Create3DTextLabel. |
| playerid | ID gracza, do którego tekst 3D ma zostać przyczepiony. |
| OffsetX | Offset X gracza. |
| OffsetY | Offset Y gracza. |
| OffsetZ | Offset Z gracza. |
## Zwracane wartości
1: Funkcja wykonała się prawidłowo.
0: Funkcja nie wykonała się prawidłowo. Oznacza to, że gracz i/lub tekst 3D nie istnieją.
## Przykłady
```c
public OnPlayerConnect(playerid)
{
new Text3D:textLabel = Create3DTextLabel("Hej, jestem tu nowy!", 0x008080FF, 30.0, 40.0, 50.0, 40.0, 0);
Attach3DTextLabelToPlayer(textLabel, playerid, 0.0, 0.0, 0.7);
return 1;
}
```
## Powiązane funkcje
- [Create3DTextLabel](Create3DTextLabel.md): Tworzy tekst 3D.
- [Delete3DTextLabel](Delete3DTextLabel.md): Kasuje tekst 3D.
- [Attach3DTextLabelToVehicle](Attach3DTextLabelToVehicle.md): Przyczepia tekst 3D do pojazdu.
- [Update3DTextLabelText](Update3DTextLabelText.md): Zmienia treść tekstu 3D.
- [CreatePlayer3DTextLabel](CreatePlayer3DTextLabel.md): Tworzy tekst 3D dla konkretnego gracza.
- [DeletePlayer3DTextLabel](DeletePlayer3DTextLabel.md): Kasuje tekst 3D danego gracza.
- [UpdatePlayer3DTextLabelText](UpdatePlayer3DTextLabel.md): Zmienia treść tekstu 3D danego gracza.
| openmultiplayer/web/docs/translations/pl/scripting/functions/Attach3DTextLabelToPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pl/scripting/functions/Attach3DTextLabelToPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 879
} | 392 |
---
title: OnNPCDisconnect
description: Essa callback é executada quando um NPC é desconectado do servidor.
tags: []
---
## Descrição
Essa callback é executada quando um NPC é desconectado do servidor.
| Nome | Descrição |
| ------------ | ------------------------------------------------------- |
| reason[] | The reason why the bot has disconnected from the server |
## Exemplos
```c
public OnNPCDisconnect(reason[])
{
printf("Desconectado do servidor. Motivo: %s", reason);
}
```
## Callbacks Relacionadas
- [OnNPCConnect](../callbacks/OnNPCConnect): Executada quando um NPC conecta no servidor.
- [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect): Executada quando o jogador desconecta do servidor.
- [OnPlayerConnect](../callbacks/OnPlayerConnect): Executada quando o jogador conecta no servidor.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnNPCDisconnect.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnNPCDisconnect.md",
"repo_id": "openmultiplayer",
"token_count": 320
} | 393 |
---
title: OnPlayerEditObject
description: Esta callback é chamada quando um jogador termina de editar um objeto (EditObject/EditPlayerObject).
tags: ["player"]
---
## Descição
Esta callback é chamada quando um jogador termina de editar um objeto (EditObject/EditPlayerObject).
| Name | Descrição |
|------------------------|---------------------------------------------------------------|
| playerid | O ID do jogador que edtiou um objeto |
| playerobject | 0 se for global, ou 1 se for um playerobject. |
| objectid | O ID do objeto que foi editado. |
| EDIT_RESPONSE:response | O [tipo de resposta](../resources/objecteditionresponsetypes) |
| Float:fX | O desclocamento de X para o objeto editado. |
| Float:fY | O desclocamento de Y para o objeto editado. |
| Float:fZ | O desclocamento de Z para o objeto editado. |
| Float:fRotX | A rotação de X para o objeto editado. |
| Float:fRotY | A rotação de Y para o objeto editado. |
| Float:fRotZ | A rotação de Z para o objeto editado. |
## 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
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) // Se for um objeto global, sincronize a posição para os outros jogadores
{
if (!IsValidObject(objectid))
{
return 1;
}
SetObjectPos(objectid, fX, fY, fZ);
SetObjectRot(objectid, fRotX, fRotY, fRotZ);
}
switch (response)
{
case EDIT_RESPONSE_FINAL:
{
// O jogador clicou no botão de salvar
// Faça qualquer coisa aqui para salvar o objeto (posição, rotação etc.)
}
case EDIT_RESPONSE_CANCEL:
{
//O jogador canceloun então coloque o objeto de volta na velha posição
if (!playerobject) //Object is not a playerobject
{
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;
}
```
## Notas
:::warning
Ao usar 'EDIT_RESPONSE_UPDATE' fique ciente que esta callback não será chamada quando sair de uma edição em progresso resultando na última atualização do 'EDIT_RESPONSE_UPDATE' ficando fora de sincronia com os objetos.
:::
## Funções Relacionadas
- [EditObject](../functions/EditObject.md): Edita um objeto.
- [CreateObject](../functions/CreateObject.md): Cria um objeto.
- [DestroyObject](../functions/DestroyObject.md): Destroi um objeto.
- [MoveObject](../functions/MoveObject.md): Move um objeto.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerEditObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerEditObject.md",
"repo_id": "openmultiplayer",
"token_count": 1742
} | 394 |
---
title: OnPlayerRequestDownload
description: Esta callback é chamada quando um jogador solicita o download de modelos personalizados.
tags: ["player"]
---
<VersionWarnPT name='callback' version='SA-MP 0.3.DL R1' />
## Descrição
Esta callback é chamada quando um jogador solicita o download de modelos personalizados.
| Nome | Descrição |
| -------- | ------------------------------------------------------ |
| playerid | O ID do jogador que solicitou o download de um modelo. |
| type | O tipo de solicitação (veja abaixo). |
| crc | O CRC de soma de verificação dos modelos. |
## Retornos
0 - Nega o download do modelo
1 - Aceita o download requisitado
## Exemplos
```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;
}
```
## Funções Relacionadas
- [OnPlayerFinishedDownloading](OnPlayerFinishedDownloading): Chamada quando um jogador termina de baixar os modelos personalizados.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerRequestDownload.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnPlayerRequestDownload.md",
"repo_id": "openmultiplayer",
"token_count": 686
} | 395 |
---
title: OnVehicleDeath
description: Essa callback é executada quando o veículo é destruído - seja explodindo ou submergindo na água.
tags: ["vehicle"]
---
## Descrição
Essa callback é executada quando o veículo é destruído - seja explodindo ou submergindo na água.
| Nome | Descrição |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vehicleid | ID do veículo que foi destruído. |
| killerid | ID do jogador que causou (sincronizadamente) a destruição do veículo (não é 100% preciso). Geralmente o motorista, passageiro (caso tenha) ou o jogador mais próximo. |
## Retornos
Sempre executada primeiro nos filterscripts.
## Exemplos
```c
public OnVehicleDeath(vehicleid, killerid)
{
new string[64];
format(string, sizeof(string), "O veículo %i foi destruído. Possivelmente por %i.", vehicleid, killerid);
SendClientMessageToAll(0xFFFFFFFF, string);
return 1;
}
```
## Notas
:::tip
Essa callback também será executada quando o veículo entrar na água, mesmo podendo ser "recuperado" (salvo) utilizando teleporte ou dirigindo (aciona quando o veículo está pacialmenmte submergido). A callback não será executada novamente, nesse caso o veículo pode acabar desaparecendo quando o motorista sair do mesmo, ou após um curto período de tempo.
:::
## Funções Relacionadas
- [SetVehicleHealth](../functions/SetVehicleHealth): Define a vida do veículo.
| openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnVehicleDeath.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/callbacks/OnVehicleDeath.md",
"repo_id": "openmultiplayer",
"token_count": 819
} | 396 |
---
title: AddStaticVehicleEx
description: Adiciona um veículo 'fixo' (modelos são pré-carregados para os jogadores) ao gamemode.
tags: ["vehicle"]
---
## Descrição
Adiciona um veículo 'fixo' (modelos são pré-carregados para os jogadores) ao gamemode. Diferente do AddStaticVehicle numa única maneira: permite re-spawnar após um tempo, quando o veículo estiver sem condutor.
| Nome | Descrição |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| modelid | O modelo ID para o veículo. |
| Float:spawn_X | A coordenada-X para o veículo. |
| Float:spawn_Y | A coordenada-Y para o veículo. |
| Float:spawn_Z | A coordenada-Z para o veículo. |
| Float:z_angle | Direção do veículo - Ângulo. |
| [color1](../resources/vehiclecolorid.md) | O ID da cor primária. |
| [color2](../resources/vehiclecolorid.md) | O ID da cor secundária. |
| respawn_delay | O delay em segundos, em que o carro pode permanecer sem condutor antes de re-spawnar. |
| addsiren | Adicionado na 0.3.7; Não irá funcionar em versões anteriores. Tem um valor padrão de 0. Permite que o veículo tenha uma sirene, desde que o veículo tenha buzina. |
## Retorno
O ID do veículo criado (1 - MAX_VEHICLES).
INVALID_VEHICLE_ID (65535) caso o veículo não tenha sido criado (limite de veículos alcançado ou modelo inválido).
## Exemplos
```c
public OnGameModeInit()
{
// Adiciona um Hydra (520) ao jogo, que irá re-spawnar 15 segundos após ser deixado.
AddStaticVehicleEx (520, 2109.1763, 1503.0453, 32.2887, 82.2873, -1, -1, 15);
return 1;
}
```
## Funções Relacionadas
- [AddStaticVehicle](AddStaticVehicle.md): Adiciona um veículo fixo.
- [CreateVehicle](CreateVehicle.md): Cria um veículo.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AddStaticVehicleEx.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/AddStaticVehicleEx.md",
"repo_id": "openmultiplayer",
"token_count": 2086
} | 397 |
---
title: DestroyActor
description: Destrói um ator que foi criado com CreateActor.
tags: []
---
Esta função foi implementada no SA-MP 0.3.7 e não funcionará em versões anteriores.
## Descrição
Destrói um ator que foi criado com CreateActor.
| Nome | Descrição |
| ------- | -------------------------------------------------------- |
| actorid | O ID do ator a ser destruído. Retornado por CreateActor. |
## Retorno
1: A função foi executada com sucesso.
0: A função falhou ao ser executada. o Ator com o ID especificado não existe.
## Exemplos
```c
new MyActor;
public OnFilterScriptInit()
{
MyActor = CreateActor(...);
return 1;
}
public OnFilterScriptExit()
{
DestroyActor(MyActor);
return 1;
}
```
## Funções Relacionadas
- [CreateActor](CreateActor.md): Cria um ator (NPC fixo).
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/DestroyActor.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/DestroyActor.md",
"repo_id": "openmultiplayer",
"token_count": 355
} | 398 |
---
title: GetNetworkStats
description: Obtém as estatísticas da rede do servidor e as armazena em uma string.
tags: []
---
## Descrição
Obtém as estatísticas da rede do servidor e as armazena em uma string.
| Nome | Descrição |
| ----------- | ------------------------------------------------------------------------ |
| retstr[] | A string para armazenar as estatísticas da rede, passado por referência. |
| retstr_size | O comprimento da string a ser armazenada. |
## Retorno
Esta função sempre retorna 1.
## Exemplos
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext, "/netstats"))
{
new stats[400+1];
GetNetworkStats(stats, sizeof(stats)); // Obtém as estatísticas da rede do servidor.
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
```
## Funções Relacionadas
- [GetPlayerNetworkStats](GetPlayerNetworkStats): Obtém as estatísticas de rede de um jogador e as salva em uma string.
- [NetStats_GetConnectedTime](NetStats_GetConnectedTime): Obtém o tempo que um jogador es Get the time that a player has been connected for.
- [NetStats_MessagesReceived](NetStats_MessagesReceived): Get the number of network messages the server has received from the player.
- [NetStats_BytesReceived](NetStats_BytesReceived): Get the amount of information (in bytes) that the server has received from the player.
- [NetStats_MessagesSent](NetStats_MessagesSent): Get the number of network messages the server has sent to the player.
- [NetStats_BytesSent](NetStats_BytesSent): Get the amount of information (in bytes) that the server has sent to the player.
- [NetStats_MessagesRecvPerSecond](NetStats_MessagesRecvPerSecond): Get the number of network messages the server has received from the player in the last second.
- [NetStats_PacketLossPercent](NetStats_PacketLossPercent): Obtém a percentagem de perda de pacotes (packet loss) de um jogador.
- [NetStats_ConnectionStatus](NetStats_ConnectionStatus): Obtém o status de conexão de um jogador.
- [NetStats_GetIpPort](NetStats_GetIpPort): Obtém o IP e porta de um jogador.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetNetworkStats.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/GetNetworkStats.md",
"repo_id": "openmultiplayer",
"token_count": 936
} | 399 |
---
title: SetPlayerFacingAngle
description: Define o ângulo para qual o jogador está voltado (olhando) (rotação Z).
tags: []
---
## Descrição
Define o ângulo para qual o jogador está voltado (olhando) (rotação Z).
| Nome | Descrição |
| ---------- | ------------------------------------------ |
| playerid | O ID do jogador para definir o ângulo. |
| Float: ang | O ângulo que o jogador deve estar voltado. |
## Retorno
1: A função foi executada com sucesso.
0: Falha ao executar a função. O jogador especificado não existe.
## Exemplos
```c
SetPlayerFacingAngle(playerid, 0); // Posiciona o jogador para o norte.
```
```c
norte (0)
|
(90) oeste- -east (270) (Boa maneira de lembrar: Never Eat Shredded Wheat)
|
sul (180)
```
## Notas
:::warning
Os ângulos são invertidos no GTA: SA; 90 graus seria o leste no mundo real, mas no GTA: SA 90 graus seria na verdade o oeste. Norte e Sul ainda são 0/360 e 180. Para converter isso, basta fazer 360 - ângulo.
:::
## Funções Relacionadas
- [GetPlayerFacingAngle](GetPlayerFacingAngle.md): Verifica para onde o jogador está voltado.
- [SetPlayerPos](SetPlayerPos.md): Define a posição de um jogador.
| openmultiplayer/web/docs/translations/pt-BR/scripting/functions/SetPlayerFacingAngle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/functions/SetPlayerFacingAngle.md",
"repo_id": "openmultiplayer",
"token_count": 533
} | 400 |
---
title: "Diretivas"
---
As diretivas são instruções passadas ao compilador para controlar como ele interpreta seu código fonte.
## `#assert`
Isto verifica se a expressão constante é verdadeira e se não aborta a compilação.
```c
#define MOO 10
#assert MOO > 5
```
Isso irá compilar corretamente.
```c
#define MOO 1
#assert MOO > 5
```
Isso não vai dar e dará um erro fatal. Isto é semelhante a:
```c
#define MOO 1
#if MOO <= 5
#error MOO check failed
#endif
```
No entanto, a afirmação dará um erro:
```
Assertation failed: 1 > 5
```
Onde o segundo dará um erro:
```
User error: Moo check failed
```
O que pode ou não ser útil.
## `#define`
`#define` é uma diretiva de substituição de texto, onde quer que o primeiro símbolo da definição seja encontrado, o resto será colocado.
```c
#define MOO 7
printf("%d", MOO);
```
Será mudado para:
```c
printf("%d", 7);
```
É por isso que todas as definições se perdem na descompilação, pois não existem quando o código é compilado (todas as diretivas são pré-processadas). As definições não têm que conter números:
```c
#define PL new i = 0; i < MAX_PLAYERS; i++) if (IsPlayerConnected(i)
for(PL) printf("%d connected", i);
```
Compilará para o loop de 1000, mais conhecido como Player Loop que todos nós conhecemos e amamos(e desprezamos). Observe como os parênteses são usados aqui, alguns do loop 'for' e outros do macro definido (o substituto).
Outro fato pouco conhecido sobre as definições é que elas podem ser multi-linhas se você pular da nova linha. Geralmente uma nova linha termina a definição, no entanto, o seguinte é válido:
```c
#define PL \
new i = 0; i < MAX_PLAYERS; i++) \
if (IsPlayerConnected(i)
printf("%d", MOO(6));
```
Isso resultará em 42 (não, não é escolhido aleatoriamente). Notou os parênteses excessivos na definição? Isto porque as definições são substituições de texto reto, de modo que serão compiladas como:
```c
printf("%d", ((6) * 7));
```
Está bem assim, mas olhe este exemplo:
```c
printf("%d", MOO(5 + 6));
```
Você esperaria que compilasse para produzir 77 ((5 + 6) \* 7) e com os parênteses, porém sem os parênteses que você tem:
```c
#define MOO(%0) \
%0 * 7
printf("%d", MOO(5 + 6));
```
O que converte para:
```c
printf("%d", MOO(5 + 6 * 7));
```
Que, devido à ordem de operações, compila como (5 + (6 \* 7)), o que se for 47 e é muito errado.
Um fato interessante sobre os parâmetros é que, se você tem muitos, o último será todos os parâmetros extras. Assim formando:
```c
#define PP(%0,%1) \
printf(%0, %1)
PP(%s %s %s, "hi", "hello", "hi");
```
Irá imprimir de fato:
```
hi hello hi
```
Como `%1` contém "hi", "hello", "hi". Você também deve ter notado o uso de `#` para converter um literal em uma string. Esta é uma característica apenas do SA-MP e pode ser útil. Foi apenas adicionado aqui para dar uma distinta distinção entre os parâmetros.
## `#else`
`#else` É igual ao `else` comum, só que na diretiva #else.
## `#elseif`
`#elseif` É igual elseif comum, só que na diretiva #if.
```c
#define MOO 10
#if MOO == 9
printf("if");
#elseif MOO == 8
printf("else if");
#else
printf("else");
#endif
```
## `#emit`
Esta diretiva não está listada na tabela pawn-lang.pdf, entretanto, ela existe. Ela é basicamente um compilador em linha. Se você conhece AMX, você pode usar isto para colocar os opcodes AMX diretamente em seu código. A única limitação é que isso permite apenas um argumento. Sintaxe: `#emita <opcódigo>>argumento>`. `<argumento>`` pode ser um número racional, inteiro ou símbolo (local ou global) (variáveis, funções e rótulos). A lista de opcodes e seu significado pode ser encontrada em Pawn Toolkit ver. 3664.
## `#endif`
`#endif` É como se um aparelho para-se. #if não usar aparelho, tudo é somado condicionalmente até o correspondente #endif.
## `#endinput, #endscript`
Isto impede a inclusão de um único arquivo.
## `#error`
Isto serve para o compilador instantaneamente imprimir mensagem de erro personalizada. Veja #assert para um exemplo.
## `#if`
`#if` Indica para o pré-processador e se é para compilar aquele trecho de código. Pode escolher exatamente o que compilar e o que não compilar a partir daqui. Por exemplo, considere o seguinte código:
```c
#define LIMITE 10
if (LIMITE < 10)
{
printf("Limite muito baixo");
}
```
That will compile as:
```c
if (10 < 10)
{
printf("Limite muito baixo");
}
```
O que claramente nunca retornará verdadeiro e o compilador sabe disso - portanto retornará um aviso de "expressão constante". A questão é, se nunca será verdade, de que vale a pena incluí-lo de todo? Poderá simplesmente remover o código, mas depois não haverá verificações se alguém alterar o macro LIMITE e recompilar. É para isto que serve a diretiva #if. Ao contrário do normal, que dá um aviso se a expressão for constante, as expressões #if devem ser constantes. Portanto:
```c
#define LIMITE 10
#if LIMITE < 10
#error Limite muito baixo
#endif
```
Isso irá verificar que o limite não é demasiado pequeno quando se compila e se é, dará um erro de tempo de compilação, em vez de se ter de testar o modo para ver se há algo de errado. Isto também significa que não é gerado um excesso de código. Note também a falta de parênteses, pode utilizá-los, e pode precisar deles em expressões mais complexas, mas não são necessários.
Aqui está outro exemplo:
```c
#define LIMITE 10
if (LIMITE < 10)
{
printf("Limite menor que 10");
}
else
{
printf("Limite igual ou menor do que 10");
}
```
Mais uma vez, esta é uma verificação constante, que dará um aviso, mas ambas as impressões serão compiladas quando sabermos que apenas uma será executada. Usando #if isto se tornar:
```c
#define LIMITE 10
#if LIMITE < 10
printf("Limite menor que 10");
#else
printf("Limite igual ou menor que 10");
#endif
```
Dessa forma, apenas a impressão que é necessária será compilada e a outra ainda estará no seu código-fonte, caso alterem o valor do macro LIMITE e recompilem, mas não será incluída no código, uma vez que não é necessária. Esta forma também significa o inútil se não for executado sempre que o seu código for executado, o que é sempre bom.
## `#include`
Isto retira todo o código de um arquivo especificado e insere-o no seu código no ponto em que a linha include se encontra. Há dois tipos de include: relativo e sistema (termos inventados pelo autor para simplificar o que está sendo feito). Relativo inclui usar aspas duplas em torno do nome do arquivo e estão localizados em relação ao arquivo atual, portanto:
```c
#include "include.pwn"
```
incluiria o arquivo "include.pwn" do mesmo diretório que o arquivo incluindo esse arquivo. O outro tipo, sistema, inclui o arquivo do diretório "include" que está localizado ou no mesmo diretório que o compilador Pawn ou diretório pai (caminhos: "include",".../include"):
```c
#include "<include>"
```
Incluiria o arquivo "include.inc" (note a falta de extensão, pode especificar se um arquivo não for .p (não .pwn ou .inc) do diretório pawno/include (supondo que você esteja utilizando Pawno).
Ambos os tipos podem conter diretórios:
```#include <diretorio/include.pwn"
```
```c
#include <diretorio/include>
```
Ambos incluirão um arquivo de um diretório abaixo dos respectivos directórios por defeito. Se o arquivo não existir, a compilação falhará.
## `#pragma`
Esta é uma das diretivas mais complexas. Ela tem uma série de opções para controlar como seu roteiro funciona. Um exemplo de configuração pareceria:
```c
#pragma ctrlchar '$'
```
Mais uma vez, esta é uma verificação constante, que dará um aviso, mas ambas as impressões serão compiladas quando sabermos que apenas uma será executada. Usando #if isto se tornar:
| Nome | Valores | Descrição |
| ---------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| codepage | nome/valor | Define a página de codificação Unicode a utilizar para cordas. |
| comprimir | 1/0 | Sem suporte no SA-MP - não tente usá-lo. |
| depreciado | símbolo | gerou um aviso se o símbolo dado for utilizado para dizer às pessoas que há uma versão melhor disponível. |
| dinâmico | valor (geralmente uma potência de 2) | Define o tamanho da memória (em células) atribuída à pilha e à pilha. Necessário se receber um aviso de utilização de memória em excesso após a compilação. (Uma tabela estranha após a linha de copyright do compilador) |
| biblioteca | nome dll | Widley incorrectamente utilizado no SA-MP. Isto especifica a dll para obter as funções nativas definidas no ficheiro de onde é proveniente. Não define um ficheiro **como** uma biblioteca. |
| pack | 1/0 | Troque os significados de !"" e """. Ver penhor-lang.pdf para mais informações sobre cordas embaladas. |
| tamanho do separador | valor | Outra configuração largamente mal utilizada. Isto deve ser utilizado para definir o tamanho de um separador para evitar avisos de compilação que estejam errados devido a espaços e separadores serem utilizados alternadamente. Isto é definido para 4 em SA:MP, pois é o tamanho de uma tabulação em pawno. Definindo este valor como 0 irá suprimir todos os seus avisos de indentação, mas é altamente desaconselhável uma vez que permite um código totalmente ilegível. |
| não utilizado | símbolo | como depreciado isto aparece após o símbolo para o qual se deseja suprimir o aviso "símbolo nunca é utilizado". Geralmente, o método preferido para o fazer é a utilização de stock, no entanto, isto nem sempre é aplicável (por exemplo, os parâmetros da função não podem ser compilados).
### Descontinuado
```c
new
gOldVariable = 5;
#pragma deprecated gOldVariable
main() {printf("%d", gOldVariable);}
```
Isso dará um aviso de que a gOldVariable não deve mais ser usada. Isto é útil principalmente para funções que preservam a compatibilidade com o passado enquanto atualizam o API.
### `#tryinclude`
Isso é semelhante a #include, mas se o arquivo não existir, a compilação não falhará. Isso é útil apenas para incluir recursos em seu script se uma pessoa tiver o plugin correto instalado(Ou pelo menos o plugin incluído)
**myinc.inc**
```c
#if defined _MY_INC_INC
#endinput
#endif
#define _MY_INC_INC
stock MinhaIncludeFunc() {printf("Olá!");}
```
**Gamemode:**
```c
#tryinclude <minhainc>
main()
{
#if defined _MINHA_INC_INC
MinhaIncludeFunc();
#endif
}
```
Isso só chamará a função MinhaIncludeFunc se o arquivo com ele for encontrado na pasta includes e compilado com sucesso. Isso, como afirmado anteriormente, é bom para plugins padrões (Por exemplo a_samp.inc ou a_actors.inc) para verificar se o desenvolvedor realmente tem o plugin instalado.
### `#undef`
Remove um macro ou simbolo constante anteriormente definido.
```c
#define MOO 10
printf("%d", MOO);
#undef MOO
printf("%d", MOO);
```
Irá falhar ao compilar, pois o macro MOO não existe.
```c
enum {
e_example = 300
};
printf("%d", e_example);
#undef e_example
printf("%d", e_example); // fatal error
```
| openmultiplayer/web/docs/translations/pt-BR/scripting/language/Directives.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/pt-BR/scripting/language/Directives.md",
"repo_id": "openmultiplayer",
"token_count": 5924
} | 401 |
---
title: OnPlayerClickMap
description: OnPlayerClickMap este apelat atunci când un jucător plasează o țintă/un punct de referință pe harta meniului de pauză (făcând clic dreapta).
tags: ["player"]
---
## Descriere
OnPlayerClickMap este apelat atunci când un jucător plasează o țintă/un punct de referință pe harta meniului de pauză (făcând clic dreapta).
| Nume | Descriere |
| -------- | ----------------------------------------------------------------------------- |
| playerid | ID-ul jucătorului care a plasat o țintă/un punct de referință |
| Float:fX | Coordonata X unde a făcut clic jucătorul |
| Float:fY | Coordonata Y unde a făcut clic jucătorul |
| Float:fZ | Coordonata Z în care jucătorul a făcut clic (inexacte - vezi nota de mai jos) |
## Returnări
1 - Va împiedica alte filterscript-uri să primească acest callback.
0 - Indică faptul că acest callback va fi transmis următorului filterscript.
Este întotdeauna numit primul în modul de joc.
## Exemple
```c
public OnPlayerClickMap(playerid, Float:fX, Float:fY, Float:fZ)
{
SetPlayerPosFindZ(playerid, fX, fY, fZ);
return 1;
}
```
## Note
:::tip
După cum spune și numele callback-ului, este apelat numai atunci când jucătorul face clic pentru a marca ținta și nu atunci când este apăsat tasta. Valoarea Z returnată va fi 0 (invalidă) dacă zona pe care se face clic pe hartă este departe de jucător; utilizați pluginul MapAndreas sau ColAndreas pentru a obține o coordonată Z mai precisă.
:::
## Funcții similare | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerClickMap.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerClickMap.md",
"repo_id": "openmultiplayer",
"token_count": 809
} | 402 |
---
title: OnPlayerGiveDamage
description: Acest callback este apelat atunci când un jucător dă daune altui jucător.
tags: ["player"]
---
## Descriere
Acest callback este apelat atunci când un jucător dă daune altui jucător.
| Nume | Descriere |
|-----------------|-------------------------------------------------------------------|
| playerid | ID-ul jucătorului care a provocat daune. |
| damagedid | ID-ul jucătorului care a primit daune. |
| Float:amount | Cantitatea de sănătate/armură deteriorată s-a pierdut (combinat). |
| WEAPON:weaponid | Motivul care a cauzat dauna. |
| bodypart | [partea corpului](../resources/bodyparts) care a fost lovită. |
## Returnări
1 - Callback-ul nu va fi apelat în alte filterscript-uri.
0 - Permite apelarea acestui callback în alte filterscript-uri.
Este întotdeauna numit primul în filterscript-uri, astfel încât returnarea 1 acolo blochează alte filterscript-uri să-l vadă.
## Exemple
```c
public OnPlayerGiveDamage(playerid, damagedid, Float:amount, WEAPON:weaponid, bodypart)
{
new string[128], victim[MAX_PLAYER_NAME], attacker[MAX_PLAYER_NAME];
new weaponname[24];
GetPlayerName(playerid, attacker, sizeof (attacker));
GetPlayerName(damagedid, victim, sizeof (victim));
GetWeaponName(weaponid, weaponname, sizeof (weaponname));
format(string, sizeof(string), "%s a provocat %.0f daune lui %s, armă: %s, partea corpului: %d", attacker, amount, victim, weaponname, bodypart);
SendClientMessageToAll(0xFFFFFFFF, string);
return 1;
}
```
## Note
:::tip
Rețineți că această funcție poate fi inexactă în unele cazuri. Dacă doriți să împiedicați anumiți jucători să-și deterioreze unii pe alții, utilizați SetPlayerTeam. Armă va returna 37 (aruncător de flăcări) din orice sursă de foc (de exemplu, molotov, 18) Armă va returna 51 de la orice armă care creează o explozie (de exemplu, RPG, grenadă) playerid este singurul care poate apela înapoi. Suma este întotdeauna dauna maximă pe care o poate face armele, chiar și atunci când sănătatea rămasă este mai mică decât dauna maximă. Deci, atunci când un jucător are 100,0 de sănătate și este împușcat cu un Vultur deșert care are o valoare a daunelor de 46,2, este nevoie de 3 lovituri pentru a ucide acel jucător. Toate cele 3 lovituri vor arăta o sumă de 46,2, chiar dacă atunci când lovește ultima lovitură, jucătorului mai are doar 7,6 de sănătate.
:::
| openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerGiveDamage.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerGiveDamage.md",
"repo_id": "openmultiplayer",
"token_count": 1178
} | 403 |
---
title: OnPlayerStreamOut
description: Acest callback este apelat atunci când un jucător este transmis în flux de la clientul altui jucător.
tags: ["player"]
---
## Descriere
Acest callback este apelat atunci când un jucător este transmis în flux de la clientul altui jucător.
| Nume | Descriere |
| ----------- | ----------------------------------------------- |
| playerid | Jucătorul care a fost destreamat. |
| forplayerid | Jucătorul care a eliminat celălalt jucător. |
## Returnări
Este întotdeauna numit primul în filterscript-uri.
## Examples
```c
public OnPlayerStreamOut(playerid, forplayerid)
{
new string[80];
format(string, sizeof(string), "Computerul dvs. tocmai a descărcat ID-ul jucătorului %d", playerid);
SendClientMessage(forplayerid, 0xFF0000FF, string);
return 1;
}
```
## Note
<TipNPCCallbacks />
## Funcții similare | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerStreamOut.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnPlayerStreamOut.md",
"repo_id": "openmultiplayer",
"token_count": 395
} | 404 |
---
title: OnVehicleSpawn
description: Acest callback este apelat atunci când un vehicul reapare.
tags: ["vehicle"]
---
:::warning
Acest callback se numește **doar** când vehiculul **re**apare! CreateVehicle și AddStaticVehicle(Ex) **nu** vor declanșa acest apel invers.
:::
## Descriere
Acest callback este apelat atunci când un vehicul reapare.
| Nume | Descriere |
| --------- | ----------------------------------- |
| vehicleid | ID-ul vehiculului care a apărut. |
## Returnări
0 - Va împiedica alte filterscript-uri să primească acest apel invers.
1 - Indică faptul că acest callback va fi transmis următorului filterscript.
Este întotdeauna numit primul în filterscript-uri.
## Exemple
```c
public OnVehicleSpawn(vehicleid)
{
printf("Vehiculul %i a apărut!",vehicleid);
return 1;
}
```
## Funcții similare
- [SetVehicleToRespawn](../functions/SetVehicleToRespawn): Readuceți un vehicul.
- [CreateVehicle](../functions/CreateVehicle): creează un vehicul. | openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnVehicleSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/callbacks/OnVehicleSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 424
} | 405 |
---
title: "Cuvant: Initializare"
---
## `const`
```c
new const
MY_CONSTANT[] = {1, 2, 3};
```
const nu este utilizat pe scară largă, însă declară o variabilă care nu poate fi modificată prin cod. Există câteva utilizări pentru aceasta - funcțiile cu parametrii matricei const pot fi uneori compilate mai eficient sau este posibil să doriți ceva de genul a defini, dar care este o matrice. const este un modificator, trebuie să meargă cu un declarator de variabile nou sau altul. Dacă încercați să modificați o variabilă const, compilatorul se va plânge.
## `enum`
Enumerările sunt un sistem foarte util pentru reprezentarea unor grupuri mari de date și modificarea rapidă a constantelor. Există câteva utilizări principale - înlocuirea seturilor mari de instrucțiuni de definire, reprezentarea simbolică a sloturilor matrice (acestea sunt de fapt același lucru, dar arată diferit) și crearea de noi etichete.
De departe cea mai obișnuită utilizare este definirea matricei:
```c
enum E_MY_ARRAY
{
E_MY_ARRAY_MONEY,
E_MY_ARRAY_GUN
}
new
gPlayerData[MAX_PLAYERS][E_MY_ARRAY];
public OnPlayerConnect(playerid)
{
gPlayerData[playerid][E_MY_ARRAY_MONEY] = 0;
gPlayerData[playerid][E_MY_ARRAY_GUN] = 5;
}
```
Aceasta va crea o matrice cu două sloturi pentru fiecare jucător. În cel la care face referire E_MY_ARRAY_MONEY va pune 0 atunci când un jucător se conectează și 5 în E_MY_ARRAY_GUN. Fără o enumere ar arăta astfel:
```c
new
gPlayerData[MAX_PLAYERS][2];
public OnPlayerConnect(playerid)
{
gPlayerData[playerid][0] = 0;
gPlayerData[playerid][1] = 5;
}
```
Și așa compilează primul. Acest lucru este OK, cu toate acestea este mai puțin lizibil - pentru ce este slotul 0 și pentru ce este slotul 1? Și este mai puțin flexibil, ce se întâmplă dacă doriți să adăugați un alt spațiu între 0 și 1, trebuie să redenumiți toate 1s-urile în 2s, adăugați-l pe cel nou și să sperați că nu ați pierdut nimic, atunci când veți face doar un enum:
```c
enum E_MY_ARRAY
{
E_MY_ARRAY_MONEY,
E_MY_ARRAY_AMMO,
E_MY_ARRAY_GUN
}
new
gPlayerData[MAX_PLAYERS][E_MY_ARRAY];
public OnPlayerConnect(playerid)
{
gPlayerData[playerid][E_MY_ARRAY_MONEY] = 0;
gPlayerData[playerid][E_MY_ARRAY_AMMO] = 100;
gPlayerData[playerid][E_MY_ARRAY_GUN] = 5;
}
```
Recompilați și totul va fi actualizat pentru dvs.
Deci, de unde știe o enumere ce valori să dea lucrurilor? Formatul complet al unei enum este:
```c
enum NAME (modifier)
{
NAME_ENTRY_1 = value,
NAME_ENTRY_2 = value,
...
NAME_ENTRY_N = value
}
```
Oricât de mult este implicat acest lucru. În mod implicit, dacă nu specificați un modificator, acesta devine (+ = 1), aceasta înseamnă că fiecare valoare din enum este ultima valoare din enum + 1, deci pentru:
```c
enum E_EXAMPLE
{
E_EXAMPLE_0,
E_EXAMPLE_1,
E_EXAMPLE_2
}
```
Prima valoare (E_EXAMPLE_0) este 0 (implicit dacă nu este specificată nicio altă valoare), deci a doua valoare (E_EXAMPLE_1) este 1 (0 + 1) și a treia valoare (E_EXAMPLE_2) este 2 (1 + 1). Aceasta face ca valoarea E_EXAMPLE 3 (2 + 1), numele enumului să fie și ultima valoare din enum. Dacă schimbăm modificatorul obținem valori diferite:
```c
enum E_EXAMPLE (+= 5)
{
E_EXAMPLE_0,
E_EXAMPLE_1,
E_EXAMPLE_2
}
```
In that example every value is the last value + 5 so, starting from 0 again, we get: E_EXAMPLE_0 = 0, E_EXAMPLE_1 = 5, E_EXAMPLE_2 = 10, E_EXAMPLE = 15. If you were to declare an array of:
```c
new
gEnumArray[E_EXAMPLE];
```
You would get an array 15 cells big however you would only be able to access cells 0, 5 and 10 using the enum values (you could however still use normal numbers). Lets look at another example:
```c
enum E_EXAMPLE (*= 2)
{
E_EXAMPLE_0,
E_EXAMPLE_1,
E_EXAMPLE_2
}
```
În aceasta toate valorile sunt 0. De ce? Ei bine, prima valoare implicită este 0, apoi 0 _ 2 = 0, apoi 0 _ 2 = 0 și 0 \ \* 2 = 0. Deci, cum putem corecta acest lucru? Pentru aceasta sunt utilizate valorile personalizate:
```c
enum E_EXAMPLE (*= 2)
{
E_EXAMPLE_0 = 1,
E_EXAMPLE_1,
E_EXAMPLE_2
}
```
Aceasta setează prima valoare la 1, deci ajungeți la 1, 2, 4 și 8. Crearea unui tablou cu care vă va oferi un tablou de 8 celule cu acces numit la celulele 1, 2 și 4. Puteți seta oricare dintre valorile dvs. și cât de multe valori doriți:
```c
enum E_EXAMPLE (*= 2)
{
E_EXAMPLE_0,
E_EXAMPLE_1 = 1,
E_EXAMPLE_2
}
```
Rezultand:
```c
0, 1, 2, 4
```
Cat timp:
```c
enum E_EXAMPLE (*= 2)
{
E_EXAMPLE_0 = 1,
E_EXAMPLE_1 = 1,
E_EXAMPLE_2 = 1
}
```
Rezulta:
```c
1, 1, 1, 2
```
Nu este recomandat să folosiți altceva decât + = 1 pentru tablouri.
De asemenea, puteți utiliza tablouri în enumerări:
```c
enum E_EXAMPLE
{
E_EXAMPLE_0[10],
E_EXAMPLE_1,
E_EXAMPLE_2
}
```
Acest lucru ar face E_EXAMPLE_0 = 0, E_EXAMPLE_1 = 10, E_EXAMPLE_2 = 11 și E_EXAMPLE = 12, contrar credinței populare de 0, 1, 2 și 3.
articolele enumere pot avea, de asemenea, etichete, deci pentru un exemplu original:
```c
enum E_MY_ARRAY
{
E_MY_ARRAY_MONEY,
E_MY_ARRAY_AMMO,
Float:E_MY_ARRAY_HEALTH,
E_MY_ARRAY_GUN
}
new
gPlayerData[MAX_PLAYERS][E_MY_ARRAY];
public OnPlayerConnect(playerid)
{
gPlayerData[playerid][E_MY_ARRAY_MONEY] = 0;
gPlayerData[playerid][E_MY_ARRAY_AMMO] = 100;
gPlayerData[playerid][E_MY_ARRAY_GUN] = 5;
gPlayerData[playerid][E_MY_ARRAY_HEALTH] = 50.0;
}
```
Acest lucru nu va da o nepotrivire a etichetei.
Enumurile pot fi folosite și ca etichete:
```c
enum E_MY_TAG (<<= 1)
{
E_MY_TAG_NONE,
E_MY_TAG_VAL_1 = 1,
E_MY_TAG_VAL_2,
E_MY_TAG_VAL_3,
E_MY_TAG_VAL_4
}
new
E_MY_TAG:gMyTagVar = E_MY_TAG_VAL_2 | E_MY_TAG_VAL_3;
```
Aceasta va crea o nouă variabilă și îi va atribui valoarea 6 (4 | 2) și va avea o etichetă personalizată astfel:
```c
gMyTagVar = 7;
```
Va genera un avertisment de nepotrivire a etichetelor, deși puteți utiliza suprascrierea etichetelor pentru a o ocoli:
```c
gMyTagVar = E_MY_TAG:7;
```
Acest lucru poate fi foarte util pentru datele de semnalizare (adică un bit pentru unele date) sau chiar pentru date combinate:
```c
enum E_MY_TAG (<<= 1)
{
E_MY_TAG_NONE,
E_MY_TAG_MASK = 0xFF,
E_MY_TAG_VAL_1 = 0x100,
E_MY_TAG_VAL_2,
E_MY_TAG_VAL_3,
E_MY_TAG_VAL_4
}
new
E_MY_TAG:gMyTagVar = E_MY_TAG_VAL_2 | E_MY_TAG_VAL_3 | (E_MY_TAG:7 & E_MY_TAG_MASK);
```
Care va produce o valoare de 1543 (0x0607).
În cele din urmă, după cum sa menționat inițial, enumurile pot fi folosite pentru a înlocui definițiile prin angajarea numelui:
```c
#define TEAM_NONE 0
#define TEAM_COP 1
#define TEAM_ROBBER 2
#define TEAM_CIV 3
#define TEAM_CLERK 4
#define TEAM_DRIVER 5
```
Sunt sigur că mulți dintre voi au văzut o mulțime de lucruri de genul acesta pentru a defini echipe. Totul este bine, dar este foarte static. Acest lucru poate fi ușor înlocuit cu un enum pentru a gestiona automat alocările numerice:
```c
enum
{
TEAM_NONE,
TEAM_COP,
TEAM_ROBBER,
TEAM_CIV,
TEAM_CLERK,
TEAM_DRIVER
}
```
Toate au aceleași valori ca și înainte și pot fi utilizate exact în același mod:
```c
new
gPlayerTeam[MAX_PLAYERS] = {TEAM_NONE, ...};
public OnPlayerConnect(playerid)
{
gPlayerTeam[playerid] = TEAM_NONE;
}
public OnPlayerRequestSpawn(playerid)
{
if (gPlayerSkin[playerid] == gCopSkin)
{
gPlayerTeam[playerid] = TEAM_COP;
}
}
```
În timp ce ne referim la subiect, există o modalitate mult mai bună de a defini echipele pe baza acestei metode:
```c
enum (<<= 1)
{
TEAM_NONE,
TEAM_COP = 1,
TEAM_ROBBER,
TEAM_CIV,
TEAM_CLERK,
TEAM_DRIVER
}
```
Acum TEAM_COP este 1, TEAM_ROBBER este 2, TEAM_CIV este 4 etc, care în binar este 0b00000001, 0b00000010 și 0b00000100. Aceasta înseamnă că, dacă echipa unui jucător este de 3, atunci se află atât în echipa de polițiști, cât și în echipa de tâlhari. Poate suna inutil, dar deschide posibilități:
```c
enum (<<= 1)
{
TEAM_NONE,
TEAM_COP = 1,
TEAM_ROBBER,
TEAM_CIV,
TEAM_CLERK,
TEAM_DRIVER,
TEAM_ADMIN
}
```
Folosind acest lucru, puteți fi atât într-o echipă normală, cât și în echipa de administratori, utilizând doar o singură variabilă. Evident, este necesară o mică modificare a codului, dar este ușor:
Pentru a adăuga un jucător la o echipă:
```c
gPlayerTeam[playerid] |= TEAM_COP;
```
Pentru a elimina un jucător dintr-o echipă:
```c
gPlayerTeam[playerid] &= ~TEAM_COP;
```
Pentru a verifica dacă un jucător face parte dintr-o echipă:
```c
if (gPlayerTeam[playerid] & TEAM_COP)
```
Foarte simplu și foarte util.
## `forward`
forward îi spune compilatorului că o funcție vine mai târziu. Este necesar pentru toate funcțiile publice, totuși poate fi utilizat în alte locuri. Utilizarea sa este „forward” urmată de numele complet și parametrii funcției pe care doriți să o redirecționați, urmată de un punct și virgulă:
```c
forward MyPublicFunction(playerid, const string[]);
public MyPublicFunction(playerid, const string[])
{
}
```
Pe lângă faptul că este necesar pentru toate publicurile înainte, poate fi folosit pentru a remedia un avertisment rar atunci când o funcție care returnează un rezultat de etichetă (de exemplu, un float) este utilizată înainte de a fi declarată.
```c
main()
{
new
Float:myVar = MyFloatFunction();
}
Float:MyFloatFunction()
{
return 5.0;
}
```
Acest lucru va da un avertisment de reparare deoarece compilatorul nu știe cum să convertească returnarea funcției într-un float, deoarece nu știe dacă funcția returnează un număr normal sau un float. În mod clar, în acest exemplu, returnează un float. Acest lucru poate fi rezolvat fie prin plasarea funcției într-un punct din cod înainte de a fi utilizată:
```c
Float:MyFloatFunction()
{
return 5.0;
}
main()
{
new
Float:myVar = MyFloatFunction();
}
```
Sau prin redirecționarea funcției, astfel încât compilatorul să știe ce să facă:
```c
forward Float:MyFloatFunction();
main()
{
new
Float:myVar = MyFloatFunction();
}
Float:MyFloatFunction()
{
return 5.0;
}
```
Nota ca forward include si tagul pentru returnare.
## `native`
O funcție nativă este una definită în mașina virtuală (adică lucrul care rulează scriptul), nu în scriptul în sine. Puteți defini funcții native numai dacă sunt codificate în SA: MP sau într-un plugin, totuși puteți crea nativi falși. Deoarece funcțiile native din fișierele .inc sunt detectate de pawno și listate în caseta din partea dreaptă a pawno, poate fi util să folosiți native pentru a obține propriile funcții personalizate listate acolo. O declarație nativă normală ar putea arăta astfel:
```c
native printf(const format[], {Float,_}:...);
```
Dacă doriți ca propriile funcții să apară fără a fi declarate native, puteți face:
```c
/*
native MyFunction(playerid);
*/
```
PAWNO nu recunoaște astfel de comentarii, așa că va adăuga funcția la listă, dar compilatorul recunoaște astfel de comentarii, așa că va ignora declarația.
Celălalt lucru interesant pe care îl poți face cu nativ este funcțiile de redenumire / suprasarcină:
```c
native my_print(const string[]) = print;
```
Acum funcția de tipărire nu există de fapt. Se află încă în SA: MP, iar compilatorul știe că este numele real datorită părții "= print", dar dacă încercați să o apelați în PAWN, veți primi o eroare, deoarece ați redenumit printul intern la my_print. Deoarece imprimarea nu există acum, o puteți defini la fel ca orice altă funcție:
```c
print(const string[])
{
my_print("Someone called print()");
my_print(string);
}
```
Acum, de fiecare dată când print () este utilizat într-un script, funcția dvs. va fi apelată în locul originalului și puteți face ceea ce doriți. În acest caz este imprimat mai întâi un alt mesaj, apoi mesajul original.
## `new`
Acesta este nucleul variabilelor, unul dintre cele mai importante cuvinte cheie despre. new declară o nouă variabilă:
```c
new
myVar = 5;
```
Aceasta va crea o variabilă, o va numi myVar și îi va atribui valoarea 5. În mod implicit, toate variabilele sunt 0 dacă nu este specificat nimic:
```c
new
myVar;
printf("%d", myVar);
```
Va da „0”.
Domeniul de aplicare al unei variabile este locul în care poate fi utilizată. Domeniul de aplicare este restricționat de paranteze (parantezele curlate - {}), orice variabilă declarată în interiorul unui set de paranteze poate fi utilizată numai în acele paranteze.
```c
if (a == 1)
{
// Braces start the line above this one
new
myVar = 5;
// This printf is in the same braces so can use myVar.
printf("%d", myVar);
// This if statement is also within the braces, so it and everything in it can use myVar
if (myVar == 1)
{
printf("%d", myVar);
}
// The braces end the line below this
}
// This is outside the braces so will give an error
printf("%d", myVar);
```
Exemplul de mai sus arată, de asemenea, de ce este atât de importantă indentarea corectă.
Dacă o variabilă globală (adică una declarată în afara unei funcții) este declarată nouă, ea poate fi utilizată peste tot după declarație:
File1.pwn:
```c
MyFunc1()
{
// Error, gMyVar doesn't exist yet
printf("%d", gMyVar);
}
// gMyVar is declared here
new
gMyVar = 10;
MuFunc2()
{
// Fine as gMyVar now exists
printf("%d", gMyVar);
}
// Include another file here
#include "file2.pwn"
```
file2.pwn:
```c
MyFunc3()
{
// This is also fine as this file is included in the first file after the declaration and new is not file restricted
printf("%d", gMyVar);
}
```
## `operator`
Acest lucru vă permite să supraîncărcați operatorii pentru etichete personalizate. De exemplu:
```c
stock BigEndian:operator=(b)
{
return BigEndian:(((b >>> 24) & 0x000000FF) | ((b >>> 8) & 0x0000FF00) | ((b << 8) & 0x00FF0000) | ((b << 24) & 0xFF000000));
}
main()
{
new
BigEndian:a = 7;
printf("%d", _:a);
}
```
Numerele normale de amanet sunt stocate în ceea ce se numește mic endian. Acest operator vă permite să definiți o sarcină pentru a converti un număr normal într-un număr mare endian. Diferența dintre endianul mare și endianul mic este ordinea de octeți. 7 în endian mic este stocat ca:
```c
07 00 00 00
```
7 este bigendian si este stocat ca:
```c
00 00 00 07
```
Prin urmare, dacă tipăriți conținutul unui număr mare endian stocat, acesta va încerca să-l citească ca un mic număr endian și să îl obțină înapoi, imprimând astfel numărul 0x07000000, aka 117440512, ceea ce veți obține dacă rulați acest cod.
Puteți supraîncărca următorii operatori:
```c
+, -, *, /, %, ++, --, ==, !=, <, >, <=, >=, ! and =
```
Rețineți, de asemenea, că îi puteți face să facă orice doriți:
```c
stock BigEndian:operator+(BigEndian:a, BigEndian:b)
{
return BigEndian:42;
}
main()
{
new
BigEndian:a = 7,
BigEndian:b = 199;
printf("%d", _:(a + b));
```
Va da pur și simplu 42, nimic de-a face cu adăugarea.
## `public`
public este utilizat pentru a face o funcție vizibilă mașinii virtuale, adică permite serverului SA: MP să apeleze direct funcția, în loc să permită apelarea funcției numai din interiorul scriptului PAWN. De asemenea, puteți face variabile publice pentru a le citi și scrie valorile de pe server, totuși acest lucru nu este folosit niciodată în SA: MP (deși s-ar putea să îl puteți utiliza dintr-un plugin, nu am încercat niciodată) (puteți combina și acest lucru cu const pentru a crea o variabilă care poate fi modificată DOAR de pe server).
O funcție publică are numele său text stocat în fișierul amx, spre deosebire de funcțiile normale care își au adresa stocată doar pentru salturi, ceea ce reprezintă un alt dezavantaj al decompilării. Aceasta este astfel încât să puteți apela funcția după nume din afara scriptului, vă permite, de asemenea, să apelați funcțiile după nume din interiorul scriptului, ieșind și reintroducându-l. Un apel de funcție nativă este aproape opusul unui apel de funcție publică, apelează o funcție din afara scriptului din interiorul scriptului, spre deosebire de apelarea unei funcții din interiorul scriptului din afara scriptului. Dacă combinați cele două, veți obține funcții precum SetTimer, SetTimerEx, CallRemoteFunction și CallLocalFunction care apelează funcții după nume, nu adresă.
Apelarea unei funcții după nume:
```c
forward MyPublicFunc();
main()
{
CallLocalFunction("MyPublicFunc", "");
}
public MyPublicFunc()
{
printf("Hello");
}
```
Funcțiile public prefixate fie cu „public”, fie cu „@” și, așa cum se menționează în secțiunea forward, toate necesită redirecționare:
```c
forward MyPublicFunc();
forward @MyOtherPublicFunc(var);
main()
{
CallLocalFunction("MyPublicFunc", "");
SetTimerEx("@MyOtherPublicFunc", 5000, 0, "i", 7);
}
public MyPublicFunc()
{
printf("Hello");
}
@MyOtherPublicFunc(var)
{
printf("%d", var);
}
```
Evident, acest exemplu a introdus SetTimerEx pentru a apela „MyOtherPublicFunc” după 5 secunde și a-i da valoarea întreagă 7 pentru a imprima.
main, utilizat în majoritatea acestor exemple, este similar cu o funcție publică prin aceea că poate fi apelată din afara scriptului, totuși nu este o funcție publică - are doar o adresă cunoscută specială, astfel încât serverul să știe unde să treacă la rulați-l.
Toate apelurile de apelare SA: MP sunt publice și sunt apelate automat din afara scriptului:
```c
public OnPlayerConnect(playerid)
{
printf("%d connected", playerid);
}
```
Când cineva se alătură serverului, acesta va căuta automat această funcție publică în toate scripturile (mai întâi modul de joc, apoi filtrează scripturile) și, dacă îl găsește, îl apelează.
Dacă doriți să apelați o funcție publică din interiorul scriptului, totuși nu trebuie să o apelați după nume, funcțiile publice se comportă și ca funcții normale:
```c
forward MyPublicFunc();
main()
{
MyPublicFunc();
}
public MyPublicFunc()
{
printf("Hello");
}
```
Acest lucru este, evident, mult mai rapid decât utilizarea CallLocalFunction sau a altui nativ.
## `static`
O variabilă statică este ca o nouă variabilă globală, dar cu un domeniu de aplicare mai limitat. Când statica este utilizată global, variabilele create rezultate sunt limitate doar la secțiunea în care au fost create (a se vedea # secțiune). Așadar, luând exemplul „nou” anterior:
file1.pwn
```c
MyFunc1()
{
// Error, gMyVar doesn't exist yet
printf("%d", gMyVar);
}
// gMyVar is declared here
new
gMyVar = 10;
MuFunc2()
{
// Fine as gMyVar now exists
printf("%d", gMyVar);
}
// Include another file here
#include "file2.pwn"
```
file2.pwn
```c
MyFunc3()
{
// This is also fine as this file is included in the first file after the declaration and new is not file restricted
printf("%d", gMyVar);
}
```
Și modificarea acestuia pentru statică ar da:
file1.pwn
```c
MyFunc1()
{
// Error, g_sMyVar doesn't exist yet
printf("%d", g_sMyVar);
}
// g_sMyVar is declared here
static
g_sMyVar = 10;
MuFunc2()
{
// Fine as _sgMyVar now exists
printf("%d", g_sMyVar);
}
// Include another file here
#include "file2.pwn"
```
file2.pwn
```c
MyFunc3()
{
// Error, g_sMyVar is limited to only the file (or section) in which it was declared, this is a different file
printf("%d", g_sMyVar);
}
```
Aceasta înseamnă că puteți avea doi globali cu același nume în fișiere diferite.
Dacă utilizați static local (adică într-o funcție), atunci variabila, ca și variabilele locale create cu nou, poate fi utilizată numai în cadrul domeniului (bazat pe paranteze - consultați secțiunea despre „nou”) în care a fost declarată. Cu toate acestea, spre deosebire de variabilele „noi”, variabilele „statice” nu își pierd valoarea între apeluri.
```c
main()
{
for (new loopVar = 0; loopVar < 4; loopVar++)
{
MyFunc();
}
}
MyFunc()
{
new
i = 0;
printf("%d", i);
i++;
printf("%d", i);
}
```
De fiecare dată când funcția este numită i este resetată la 0, astfel încât ieșirea rezultată va fi:
```c
0
1
0
1
0
1
0
1
```
Dacă înlocuim „noul” cu „static” obținem:
```c
main()
{
for (new loopVar = 0; loopVar < 4; loopVar++)
{
MyFunc();
}
}
MyFunc()
{
static
i = 0;
printf("%d", i);
i++;
printf("%d", i);
}
```
Și, deoarece localnicii statici își păstrează valoarea între apeluri, rezultatul rezultat este:
```c
0
1
1
2
2
3
3
4
```
Valoarea dată în declarație (dacă este dată una, ca și variabilele statice noi, implicite la 0) este valoarea atribuită variabilei la prima apelare a funcției. Deci, dacă „static i = 5;” au fost folosite în schimb, rezultatul ar fi:
```c
5
6
6
7
7
8
8
9
```
Datorită modului în care sunt stocate variabilele statice, ele sunt de fapt variabile globale, compilatorul verifică dacă sunt utilizate în locul corect. Ca urmare, scripturile decompilate nu pot face distincție între globale normale, statici globale și statici locale și toate sunt date ca globale normale.
De asemenea, puteți avea funcții statice care pot fi apelate numai din fișierul în care sunt declarate. Acest lucru este util pentru funcțiile de stil privat.
## `stock`
stock este folosit pentru a declara variabile și funcții care nu pot fi utilizate, dar pentru care nu doriți să generați avertismente neutilizate. Cu variabilele stocul este ca const prin faptul că este un modificator, nu o declarație completă, deci ați putea avea:
```c
new stock
gMayBeUsedVar;
static stock
g_sMayBeUsedVar;
```
Dacă se utilizează variabila sau funcția, compilatorul o va include, dacă nu este utilizată, o va exclude. Acest lucru este diferit de utilizarea #pragma unused (simbol), deoarece aceasta va suprima (adică ascunde) avertismentul și va include oricum informațiile, stocul va ignora în totalitate datele neutilizate.
stockul este cel mai frecvent utilizat pentru bibliotecile personalizate. Dacă scrieți o bibliotecă, furnizați o mulțime de funcții pe care alte persoane le pot folosi, dar nu aveți nicio idee dacă le vor folosi sau nu. Dacă codul dvs. oferă o mulțime de avertismente pentru fiecare funcție pe care o persoană nu o folosește, oamenii se vor plânge (cu excepția cazului în care este intenționat, deoarece TREBUIE să folosească acea funcție (de exemplu, pentru inițializarea variabilelor). Acestea fiind spuse însă, trecând din experiența personală cu oamenii YSI se va plânge oricum.
```c
main()
{
Func1();
}
Func1()
{
printf("Hello");
}
Func2()
{
printf("Hi");
}
```
Aici Func2 nu este apelat niciodată, astfel încât compilatorul va da un avertisment. Acest lucru poate fi util deoarece ați uitat să-l numiți, așa cum se întâmplă în general într-un script direct, cu toate acestea, dacă Func1 și Func2 se află într-o bibliotecă, este posibil ca utilizatorul să nu aibă nevoie de Func2, deci faceți:
```c
main()
{
Func1();
}
stock Func1()
{
printf("Hello");
}
stock Func2()
{
printf("Hi");
}
```
Iar funcția nu va fi compilată și avertismentul eliminat.
| openmultiplayer/web/docs/translations/ro/scripting/language/Initialisers.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/language/Initialisers.md",
"repo_id": "openmultiplayer",
"token_count": 10815
} | 406 |
---
title: Status conexiune
description: Starea conexiunii de utilizat cu NetStats_ConnectionStatus.
---
## Descriere
Starea conexiunii se foloseste cu [NetStats_ConnectionStatus](../functions/NetStats_ConnectionStatus.md).
## Folosit des
| ID | Stare | Sens |
| --- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| 0 | NO_ACTION | unknown |
| 1 | DISCONNECT_ASAP | playerid still exists but [OnPlayerDisconnect](../callbacks/OnPlayerDisconnect.md) have already been called. |
| 2 | DISCONNECT_ASAP_SILENTLY | unknown |
| 3 | DISCONNECT_ON_NO_ACK | unknown |
| 4 | REQUESTED_CONNECTION | connection request "cookie" has been sent for this ID |
| 5 | HANDLING_CONNECTION_REQUEST | unknown |
| 6 | UNVERIFIED_SENDER | unknown |
| 7 | SET_ENCRYPTION_ON_MULTIPLE_16_BYTE_PACKET | unknown |
| 8 | CONNECTED | playerid is connected to the server |
| openmultiplayer/web/docs/translations/ro/scripting/resources/connectionstatus.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/scripting/resources/connectionstatus.md",
"repo_id": "openmultiplayer",
"token_count": 1364
} | 407 |
---
title: Cooldown-uri
description: Un tutorial pentru scrierea cooldown-urilor pentru limitarea acțiunilor utilizatorilor folosind numărul de bifări și evitarea utilizării cronometrelor.
---
Acest tutorial acoperă scrierea unui mecanic de joc utilizat în mod obișnuit în jocurile de acțiune: cooldowns. Un timp de răcire este un instrument pentru a limita frecvența la care un jucător poate face ceva. Poate fi vorba despre utilizarea unei abilități precum vindecarea sau scrierea mesajelor de chat. Vă permite să încetiniți ritmul cu care jucătorii fac lucruri fie în scop de echilibrare a jocului, fie pentru a preveni spamul.
Mai întâi voi exemplifica modul _bad_ de a face o răcire folosind `SetTimer` pentru a actualiza starea.
## Utilizarea timerelor
Spuneți, de exemplu, că aveți o acțiune specifică care poate fi efectuată doar o dată la atât de multe secunde, văd o mulțime de oameni (inclusiv Southclaws, acum mulți ani) care fac așa ceva:
```c
static bool:IsPlayerAllowedToDoThing[MAX_PLAYERS];
OnPlayerInteractWithServer(playerid)
/* This can be any sort of input event a player makes such as:
* Entering a command
* Picking up a pickup
* Entering a checkpoint
* Pressing a button
* Entering an area
* Using a dialog
*/
{
// This only works when the player is allowed to
if (IsPlayerAllowedToDoThing[playerid])
{
// Do the thing the player requested
DoTheThingThePlayerRequested();
// Disallow the player
IsPlayerAllowedToDoThing[playerid] = false;
// Allow the player to do the thing again in 10 seconds
SetTimerEx("AllowPlayer", 10000, false, "d", playerid);
return 1;
}
else
{
SendClientMessage(playerid, -1, "You are not allowed to do that yet!");
return 0;
}
}
// Called 10 seconds after the player does the thing
public AllowPlayer(playerid)
{
IsPlayerAllowedToDoThing[playerid] = true;
SendClientMessage(playerid, -1, "You are allowed to do the thing again! :D");
}
```
Acum totul este bine, funcționează, jucătorul nu va mai putea face acel lucru timp de 10 secunde după ce îl folosește.
Luați un alt exemplu aici, acesta este un cronometru care măsoară cât durează un jucător să facă o cursă simplă punct la punct:
```c
static
StopWatchTimerID[MAX_PLAYERS],
StopWatchTotalTime[MAX_PLAYERS];
StartPlayerRace(playerid)
{
// Calls a function every second
StopWatchTimerID[playerid] = SetTimerEx("StopWatch", 1000, true, "d", playerid);
}
public StopWatch(playerid)
{
// Increment the seconds counter
StopWatchTotalTime[playerid]++;
}
OnPlayerFinishRace(playerid)
{
new str[128];
format(str, 128, "You took %d seconds to do that", StopWatchTotalTime[playerid]);
SendClientMessage(playerid, -1, str);
KillTimer(StopWatchTimerID[playerid]);
}
```
Aceste două exemple sunt comune și pot funcționa bine. Cu toate acestea, există o modalitate mult mai bună de a obține ambele rezultate, care este mult mai precisă și poate da temporizări ale cronometrului până la milisecunde!
## Folosind `GetTickCount()` și `gettime()`
`GetTickCount()` este o funcție care vă oferă timpul în milisecunde de la deschiderea procesului serverului. `gettime()` returnează numărul de secunde de la 1 ianuarie 1970, cunoscut și sub numele de Unix Timestamp.
Dacă apelați oricare dintre aceste funcții în două momente diferite și scădeți prima dată din a doua, aveți brusc un interval între aceste două evenimente în milisecunde sau, respectiv, în secunde! Aruncați o privire la acest exemplu:
### Un cooldown
```c
static PlayerAllowedTick[MAX_PLAYERS];
OnPlayerInteractWithServer(playerid)
{
if (GetTickCount() - PlayerAllowedTick[playerid] > 10000)
// This only works when the current tick minus the last tick is above 10000.
// In other words, it only works when the interval between the actions is over 10 seconds.
{
DoTheThingThePlayerRequested();
PlayerAllowedTick[playerid] = GetTickCount(); // Update the tick count with the latest time.
return 1;
}
else
{
SendClientMessage(playerid, -1, "You are not allowed to do that yet!");
return 0;
}
}
```
Sau, alternativ, versiunea `gettime()`:
```c
static PlayerAllowedSeconds[MAX_PLAYERS];
OnPlayerInteractWithServer(playerid)
{
if (gettime() - PlayerAllowedSeconds[playerid] > 10)
// This only works when the current seconds minus the last seconds is above 10.
// In other words, it only works when the interval between the actions is over 10 seconds.
{
DoTheThingThePlayerRequested();
PlayerAllowedSeconds[playerid] = gettime(); // Update the seconds count with the latest time.
return 1;
}
else
{
SendClientMessage(playerid, -1, "You are not allowed to do that yet!");
return 0;
}
}
```
Există mult mai puțin cod acolo, nu este nevoie de o funcție publică sau de un cronometru. Dacă doriți cu adevărat, puteți pune timpul rămas în mesajul de eroare:
(Folosesc SendFormatMessage în acest exemplu)
```c
SendFormatMessage(
playerid,
-1,
"You are not allowed to do that yet! You can again in %d ms",
10000 - (GetTickCount() - PlayerAllowedTick[playerid])
);
```
Acesta este un exemplu foarte de bază, ar fi mai bine să convertiți acea valoare MS într-un șir de „minute: secunde. Milisecunde”, dar voi posta codul respectiv la sfârșit.
### Un cronometru
Sperăm că puteți vedea cât de puternic este acest lucru pentru a obține intervale între evenimente, să ne uităm la un alt exemplu
```c
static Stopwatch[MAX_PLAYERS];
StartPlayerRace(playerid)
{
Stopwatch[playerid] = GetTickCount();
}
OnPlayerFinishRace(playerid)
{
new
interval,
str[128];
interval = GetTickCount() - Stopwatch[playerid];
format(str, 128, "You took %d milliseconds to do that", interval);
SendClientMessage(playerid, -1, str);
}
```
În acest exemplu, numărul de bifă este salvat în variabila jucătorului atunci când începe cursa. Când o termină, bifa curentă (de când a terminat) are acea bifă inițială (Valoarea mai mică) scăzută din ea și astfel ne lasă cantitatea de milisecunde între începutul și sfârșitul cursei.
#### Defectiuni
Acum, să descompunem puțin codul.
```c
new Stopwatch[MAX_PLAYERS];
```
Aceasta este o variabilă globală, trebuie să o folosim astfel încât să putem salva numărul de bifuri și să recuperăm valoarea într-un alt moment (cu alte cuvinte, folosiți-o în altă funcție, mai târziu)
```c
StartPlayerRace(playerid)
{
Stopwatch[playerid] = GetTickCount();
}
```
Acesta este momentul în care jucătorul începe cursa, numărul de bifuri de acum este înregistrat, dacă acest lucru se întâmplă la 1 minut de la pornirea serverului, valoarea acelei variabile va fi 60.000, deoarece este de 60 de secunde și fiecare secundă are o mie de milisecunde.
Bine, acum avem variabila acelui jucător stabilită la 60.000, acum el termină cursa 1 minut 40 secunde mai târziu:
```c
OnPlayerFinishRace(playerid)
{
new
interval,
str[128];
interval = GetTickCount() - Stopwatch[playerid];
format(str, 128, "You took %d milliseconds to do that", interval);
SendClientMessage(playerid, -1, str);
}
```
Aici se întâmplă calculul intervalului, ei bine, spun calculul, este doar scăderea a două valori!
GetTickCount() returnează numărul curent de căpușe, deci va fi mai mare decât numărul de căpușe inițial, ceea ce înseamnă că scădeți numărul de căpușe inițial din numărul curent de căpușe pentru a obține intervalul dintre cele două măsuri.
Deci, așa cum am spus, jucătorul termină cursa 1 minut și 40 de secunde mai târziu (100 de secunde sau 100.000 de milisecunde), GetTickCount va reveni la 160.000. Scadeți valoarea inițială (care este 60.000) din noua valoare (care este 160.000) și obțineți 100.000 milisecunde, adică 1 minut 40 secunde, care este timpul necesar jucătorului pentru a face cursa!
## Recapitulare și note
Asa de! Am aflat că:
- GetTickCount returnează cantitatea de timp în milisecunde de la pornirea sistemului computer pe care rulează serverul.
- Și o putem folosi apelând-o la două intervale, salvând prima la o variabilă și comparând cele două valori vă poate oferi un interval precis în milisecunde între cele două evenimente.
Nu în ultimul rând, nu doriți să le spuneți jucătorilor valorile timpului în milisecunde! Ce se întâmplă dacă durează o oră pentru a finaliza o cursă?
Cel mai bine este să folosiți o funcție care ia milisecundele și o convertește într-un format lizibil, de exemplu, exemplul anterior, jucătorul a luat 100.000 de milisecunde pentru a face cursa, dacă i-ați spune jucătorului că a durat atât de mult, ar dura mai mult timp pentru a citi că 100.000 și dați seama ce înseamnă în timp de citit de om.
[Acest pachet](https://github.com/ScavengeSurvive/timeutil) conține o funcție de formatare a milisecundelor într-un șir.
Sper că acest lucru a ajutat! Am scris-o pentru că am ajutat recent câteva persoane care nu știau cum să folosească `GetTickCount()` sau `gettime()` ca alternativă pentru temporizatoare sau pentru obținerea de intervale etc.
| openmultiplayer/web/docs/translations/ro/tutorials/cooldowns.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ro/tutorials/cooldowns.md",
"repo_id": "openmultiplayer",
"token_count": 3864
} | 408 |
---
title: AddPlayerClass
description: Добавляет класс в выбор классов.
tags: ["player"]
---
## Описание
Добавляет класс в выбор классов. Класс служит для того, чтоб игрок мог респавниться (появиться) с выбранным скином.
| Name | Description |
| ------------- | ------------------------------------------------------------- |
| modelid | Скин с которым игрок появиться |
| Float:spawn_x | Координаты X, для точки появляения данного класса. |
| Float:spawn_y | Координаты Y, для точки появляения данного класса. |
| Float:spawn_z | Координаты Z, для точки появляения данного класса. |
| Float:z_angle | Угол направление игрока |
| weapon1 | Первое оружие игрока |
| weapon1_ammo | Патроны для первого оружия |
| weapon2 | Второе оружие игрока |
| weapon2_ammo | Патроны для второго оружия |
| weapon3 | Третье оружие игрока |
| weapon3_ammo | Патроны для третьего оружия |
## Возвращаемые данные
ID класса который был создан.
319 если лимит (320) исчерпан. Самый высокий ID для класса это 319.
## Пример
```c
public OnGameModeInit()
{
// Игроки смогут выбрать появиться со скином 0 (CJ) или со скином 1 (The Truth).
AddPlayerClass(0, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // CJ
AddPlayerClass(1, 1958.33, 1343.12, 15.36, 269.15, 26, 36, 28, 150, 0, 0); // The Truth
return 1;
}
```
## Примечания
:::tip
Максимальный ID класса 319 ( начинается с 0, что значит можно создать всего 320 классов ). В случае превышения лимита, добавленный класс будет заменять класс 319.
:::
## Связанные функции
- [AddPlayerClassEx](AddPlayerClassEx.md): Добавляет класс с указанной командой (teamid).
- [SetSpawnInfo](SetSpawnInfo.md): Установка информации для спавна игрока.
- [SetPlayerSkin](SetPlayerSkin.md): Устанавливает скин игрока.
| openmultiplayer/web/docs/translations/ru/scripting/functions/AddPlayerClass.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ru/scripting/functions/AddPlayerClass.md",
"repo_id": "openmultiplayer",
"token_count": 1749
} | 409 |
---
title: Система серверных переменных
description: Система серверных переменных (в сокращении SVar) - это новый способ динамического создания серверных переменных в глобальном пространстве, т.е. к одной переменной можно получить доступ и из игрового мода (gamemode), и из подключаемого сценария (filterscript).
---
Система **серверных переменных** (в сокращении **SVar**) - это новый способ динамического создания серверных переменных в глобальном пространстве, т.е. к одной переменной можно получить доступ и из игрового мода (gamemode), и из подключаемого сценария (filterscript).
Они работают точно так же, как [PVars](perplayervariablesystem), но не привязаны к конкретному ID игрока.
:::warning
Эта система была представлена в SA-MP 0.3.7 R2-1 и не будет работать на ранних версиях!
:::
:::note
Система SVar аналогична системе PVar, за исключением того, что SVar создаёт глобальные серверные переменные, не привязанные к ID игроков, которые не изменяются даже при смене игрового режима (gamemode).
:::
## Преимущества
- SVar'ы могут быть созданы и считаны во всех запущенных сценариях сервера (игровые режимы, скрипты, инклуды и т.д.)
- SVar легко вывести или записать куда-то с помощью перебора. Это делает отладку намного проще.
- Если попытаться получить доступ к ещё не созданной серверной переменной, она всё ещё вернёт значение по умолчанию - 0.
- В SVar можно хранить очень большие строки при помощи динамически выделяемой памяти.
- Можно устанавливать, получать и создавать SVar прямо во время игры.
## Недостатки
- SVar в несколько раз медленнее, чем обычные переменные. Как правило, предпочтительнее пожертвовать памятью, нежели скоростью, но не наоборот.
## Функции
- [SetSVarInt](../scripting/functions/SetSVarInt): установить целочисленное значение серверной переменной.
- [GetSVarInt](../scripting/functions/GetSVarInt): получить целочисленное значение серверной переменной.
- [SetSVarString](../scripting/functions/SetSVarString): установить строчное значение серверной переменной.
- [GetSVarString](../scripting/functions/GetSVarString): получить строчное значение серверной переменной.
- [SetSVarFloat](../scripting/functions/SetSVarFloat): установить число с плавающей точкой в качестве значения серверной переменной.
- [GetSVarFloat](../scripting/functions/GetSVarFloat): получить целочисленное значение серверной переменной в виде числа с плавающей точкой.
- [DeleteSVar](../scripting/functions/DeleteSVar): удалить серверную переменную.
| openmultiplayer/web/docs/translations/ru/tutorials/servervariablesystem.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/ru/tutorials/servervariablesystem.md",
"repo_id": "openmultiplayer",
"token_count": 2229
} | 410 |
# SA-MP Wiki и open.mp Документација
Добродошао на SA-MP wiki, којег одржава open.mp тим и шира SA-MP заједница!
Ова веб страница жели пружити лако доступан и једноставан допринос извору документације за SA-MP и, напослетку, open.mp.
## SA-MP wiki је нестао
Нажалост, wiki SA-MP угашен крајем септембра - иако се већина његовог садржаја може пронаћи у јавној интернетској архиви.
Потребна нам је помоћ заједнице да пренесемо стари њики садржај у свој нови дом, овде!
Ако сте заинтересовани проверите [ову страницу](/docs/meta/Contributing) за више информација.
Ако немате искуства са коришћењем GitHub-a или претварањем HTML-a, не брините! Можете нам помоћи тако што ћете нас само овавестити о проблемима (путем [Discord](https://discord.gg/samp), [форума](https://forum.open.mp) или дружтвених мрежа) и најважнија ствар _ширенје речи!_ Свакако додајете ову страницу у ваше bookmarks ознаке и поделите је са свима које познајете и који се питају камо је отишао SA-MP Wiki.
Добродошли су доприноси за побољшања документације, као и упуте и водиче за уобичајене задатке попут израде једноставних гамемодова и коришћења заједничких "libraries" и плугина. Ако сте заинтересовани за допринос, крените на [GitHub страницу](https://github.com/openmultiplayer/web).
| openmultiplayer/web/docs/translations/sr/index.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/sr/index.md",
"repo_id": "openmultiplayer",
"token_count": 1197
} | 411 |
---
title: SetPlayerArmour
description: Podesava pancir igraca.
tags: ["player"]
---
## Description
Podesava pancir igraca.
| Name | Description |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| playerid | ID igraca kome se podesava pancir |
| Float:armour | Kolicina pancira koja se daje, u procentima(float). Vrednosti vece od 100 mogu da se postave, ali se nece prikazivati u HUD-u igraca |
## Returns
1: Funkcija je uspesno izvrsena.
0: Funkcija nije uspesno izvrsena. To znaci da ID igraca koji smo uneli ne postoji.
## Examples
```c
public OnPlayerSpawn(playerid)
{
// Daje igracu maksimalan pancir (100%) na spawnu
SetPlayerArmour(playerid, 100.0);
return 1;
}
```
## Notes
:::tip
Ime funkcije je armour, ne armor (Americki).
:::
:::warning
Pancir se dobija zaokruzen na integer: postavi 50.15, ali dobijes 50.0
:::
## Related Functions
- [GetPlayerArmour](GetPlayerArmour.md): Dobija se vrednost pancira koju igrac trenutno ima.
- [SetPlayerHealth](SetPlayerHealth.md): Podesava health igracu.
- [GetPlayerHealth](GetPlayerHealth.md): Dobija se vrednost health-a koju igrac trenutno ima.
| openmultiplayer/web/docs/translations/sr/scripting/functions/SetPlayerArmour.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/sr/scripting/functions/SetPlayerArmour.md",
"repo_id": "openmultiplayer",
"token_count": 672
} | 412 |
---
title: OnPlayerClickPlayer
description: Callback นี้ถูกเรียกเมื่อผู้เล่นดับเบิลคลิกบนผู้เล่นที่กระดานคะแนน
tags: ["player"]
---
## คำอธิบาย
Callback นี้ถูกเรียกเมื่อผู้เล่นดับเบิลคลิกบนผู้เล่นที่กระดานคะแนน
| ชื่อ | คำอธิบาย |
| --------------- | ------------------------------------------- |
| playerid | ไอดีของผู้เล่นที่คลิกบนผู้เล่นบนกระดานคะแนน |
| clickedplayerid | ไอดีของผู้เล่นที่ถูกคลิก |
| source | แหล่งที่มาของการคลิกของผู้เล่น |
## ส่งคืน
1 - จะป้องกันไม่ให้ฟิลเตอร์สคริปต์อื่นถูกเรียกโดย Callback นี้
0 - บอกให้ Callback นี้ส่งต่อไปยังฟิลเตอร์สคริปต์ถัดไป
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
public OnPlayerClickPlayer(playerid, clickedplayerid, CLICK_SOURCE:source)
{
new message[32];
format(message, sizeof(message), "คุณได้คลิกบนผู้เล่น %d", clickedplayerid);
SendClientMessage(playerid, 0xFFFFFFFF, message);
return 1;
}
```
## บันทึก
:::tip
ตอนนี้ 'source' มีเพียงแค่ค่าเดียว (0 - CLICK_SOURCE_SCOREBOARD) ส่วนขยายนี้แสดงให้เห็นว่าอาจมีการรองรับข้อมูลเพิ่มเติมในอนาคต
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [OnPlayerClickTextDraw](../../scripting/callbacks/OnPlayerClickTextDraw.md): ถูกเรียกเมื่อผู้เล่นคลิกบน Textdraw
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerClickPlayer.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerClickPlayer.md",
"repo_id": "openmultiplayer",
"token_count": 1398
} | 413 |
---
title: OnPlayerGiveDamageActor
description: This callback is called when a player gives damage to an actor.
tags: ["player"]
---
:::warning
Callback นี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
This callback is called when a player gives damage to an actor.
| Name | Description |
|-----------------|-------------------------------------------------------|
| playerid | The ID of the player that gave damage. |
| damaged_actorid | The ID of the actor that received damage. |
| Float:amount | The amount of health/armour damaged_actorid has lost. |
| WEAPON:weaponid | The reason that caused the damage. |
| bodypart | The body part that was hit |
## ส่งคืน
1 - Callback will not be called in other filterscripts.
0 - Allows this callback to be called in other filterscripts.
It is always called first in filterscripts so returning 1 there blocks other filterscripts from seeing it.
## ตัวอย่าง
```c
public OnPlayerGiveDamageActor(playerid, damaged_actorid, Float:amount, WEAPON:weaponid, bodypart)
{
new string[128], attacker[MAX_PLAYER_NAME];
new weaponname[24];
GetPlayerName(playerid, attacker, sizeof (attacker));
GetWeaponName(weaponid, weaponname, sizeof (weaponname));
format(string, sizeof(string), "%s has made %.0f damage to actor id %d, weapon: %s", attacker, amount, damaged_actorid, weaponname);
SendClientMessageToAll(0xFFFFFFFF, string);
return 1;
}
```
## บันทึก
:::tip
This function does not get called if the actor is set invulnerable (WHICH IS BY DEFAULT). See [SetActorInvulnerable](../functions/SetActorInvulnerable).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreateActor](../functions/CreateActor): Create an actor (static NPC).
- [SetActorInvulnerable](../functions/SetActorInvulnerable): Set actor invulnerable.
- [SetActorHealth](../functions/SetActorHealth): Set the health of an actor.
- [GetActorHealth](../functions/GetActorHealth): Gets the health of an actor.
- [IsActorInvulnerable](../functions/IsActorInvulnerable): Check if actor is invulnerable.
- [IsValidActor](../functions/IsValidActor): Check if actor id is valid.
## Related Callbacks
- [OnActorStreamOut](OnActorStreamOut): Called when an actor is streamed out by a player.
- [OnPlayerStreamIn](OnPlayerStreamIn): Called when a player streams in for another player.
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerGiveDamageActor.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerGiveDamageActor.md",
"repo_id": "openmultiplayer",
"token_count": 1000
} | 414 |
---
title: OnPlayerTakeDamage
description: This callback is called when a player takes damage.
tags: ["player"]
---
:::warning
Callback นี้ถูกเพิ่มใน SA-MP 0.3d และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
This callback is called when a player takes damage.
| Name | Description |
| -------- | ------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player that took damage. |
| issuerid | The ID of the player that caused the damage. INVALID_PLAYER_ID if self-inflicted. |
| Float:amount | The amount of damage the player took (health and armour combined). |
| WEAPON:weaponid | The ID of the weapon/reason for the damage. |
| bodypart | The body part that was hit. |
## ส่งคืน
1 - Callback will not be called in other filterscripts.
0 - Allows this callback to be called in other filterscripts.
It is always called first in filterscripts so returning 1 there blocks other filterscripts from seeing it.
## ตัวอย่าง
```c
public OnPlayerTakeDamage(playerid, issuerid, Float:amount, WEAPON:weaponid, bodypart)
{
if (issuerid != INVALID_PLAYER_ID) // If not self-inflicted
{
new
infoString[128],
weaponName[24],
victimName[MAX_PLAYER_NAME],
attackerName[MAX_PLAYER_NAME];
GetPlayerName(playerid, victimName, sizeof (victimName));
GetPlayerName(issuerid, attackerName, sizeof (attackerName));
GetWeaponName(weaponid, weaponName, sizeof (weaponName));
format(infoString, sizeof(infoString), "%s has made %.0f damage to %s, weapon: %s, bodypart: %d", attackerName, amount, victimName, weaponName, bodypart);
SendClientMessageToAll(-1, infoString);
}
return 1;
}
```
```c
public OnPlayerTakeDamage(playerid, issuerid, Float:amount, WEAPON:weaponid, bodypart)
{
if (issuerid != INVALID_PLAYER_ID && weaponid == 34 && bodypart == 9)
{
// One shot to the head to kill with sniper rifle
SetPlayerHealth(playerid, 0.0);
}
return 1;
}
```
## บันทึก
:::tip
The weaponid will return 37 (flame thrower) from any fire sources (e.g. molotov, 18). The weaponid will return 51 from any weapon that creates an explosion (e.g. RPG, grenade) playerid is the only one who can call the callback. The amount is always the maximum damage the weaponid can do, even when the health left is less than that maximum damage. So when a player has 100.0 health and gets shot with a Desert Eagle which has a damage value of 46.2, it takes 3 shots to kill that player. All 3 shots will show an amount of 46.2, even though when the last shot hits, the player only has 7.6 health left.
:::
:::warning
GetPlayerHealth and GetPlayerArmour will return the old amounts of the player before this callback. Always check if issuerid is valid before using it as an array index.
:::
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerTakeDamage.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnPlayerTakeDamage.md",
"repo_id": "openmultiplayer",
"token_count": 1364
} | 415 |
---
title: OnVehicleStreamIn
description: Called when a vehicle is streamed to a player's client.
tags: ["vehicle"]
---
## คำอธิบาย
Called when a vehicle is streamed to a player's client.
| Name | Description |
| ----------- | ------------------------------------------------------ |
| vehicleid | The ID of the vehicle that streamed in for the player. |
| forplayerid | The ID of the player who the vehicle streamed in for. |
## ส่งคืน
มันถูกเรียกในฟิลเตอร์สคริปต์ก่อนเสมอ
## ตัวอย่าง
```c
public OnVehicleStreamIn(vehicleid, forplayerid)
{
new string[32];
format(string, sizeof(string), "You can now see vehicle %d.", vehicleid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## บันทึก
:::tip
NPC สามารถเรียก Callback นี้ได้
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleStreamIn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/callbacks/OnVehicleStreamIn.md",
"repo_id": "openmultiplayer",
"token_count": 493
} | 416 |
---
title: ApplyAnimation
description: Apply an animation to a player.
tags: []
---
## คำอธิบาย
Apply an animation to a player.
| Name | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| playerid | The ID of the player to apply the animation to. |
| animlib[] | The animation library from which to apply an animation. |
| animname[] | The name of the animation to apply, within the specified library. |
| fDelta | The speed to play the animation (use 4.1). |
| loop | If set to 1, the animation will loop. If set to 0, the animation will play once. |
| lockx | If set to 0, the player is returned to their old X coordinate once the animation is complete (for animations that move the player such as walking). 1 will not return them to their old position. |
| locky | Same as above but for the Y axis. Should be kept the same as the previous parameter. |
| freeze | Setting this to 1 will freeze the player at the end of the animation. 0 will not. |
| time | Timer in milliseconds. For a never-ending loop it should be 0. |
| forcesync | Set to 1 to make server sync the animation with all other players in streaming radius (optional). 2 works same as 1, but will ONLY apply the animation to streamed-in players, but NOT the actual player being animated (useful for npc animations and persistent animations when players are being streamed) |
## ส่งคืน
This function always returns 1, even if the player specified does not exist, or any of the parameters are invalid (e.g. invalid library).
## ตัวอย่าง
```c
ApplyAnimation(playerid, "PED", "WALK_DRUNK", 4.1, 1, 1, 1, 1, 1, 1);
```
## บันทึก
:::tip
The 'forcesync' optional parameter, which defaults to 0, in most cases is not needed since players sync animations themselves. The 'forcesync' parameter can force all players who can see 'playerid' to play the animation regardless of whether the player is performing that animation. This is useful in circumstances where the player can't sync the animation themselves. For example, they may be paused.
:::
:::warning
An invalid animation library will crash the player's game.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [ClearAnimations](../../scripting/functions/ClearAnimations.md): Clear any animations a player is performing.
- [SetPlayerSpecialAction](../../scripting/functions/SetPlayerSpecialAction.md): Set a player's special action.
| openmultiplayer/web/docs/translations/th/scripting/functions/ApplyAnimation.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ApplyAnimation.md",
"repo_id": "openmultiplayer",
"token_count": 3034
} | 417 |
---
title: CancelEdit
description: Cancel object edition mode for a player.
tags: []
---
## คำอธิบาย
Cancel object edition mode for a player
| Name | Description |
| -------- | ------------------------------------------ |
| playerid | The ID of the player to cancel edition for |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid, cmdtext[])
{
if (!strcmp(cmdtext, "/stopedit", true))
{
CancelEdit(playerid);
SendClientMessage(playerid, 0xFFFFFFFF, "SERVER: You stopped editing the object!");
return 1;
}
return 0;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SelectObject](../../scripting/functions/SelectObject.md): Select an object.
- [EditObject](../../scripting/functions/EditObject.md): Edit an object.
- [EditPlayerObject](../../scripting/functions/EditPlayerObject.md): Edit an object.
- [EditAttachedObject](../../scripting/functions/EditAttachedObject.md): Edit an attached object.
- [CreateObject](../../scripting/functions/CreateObject.md): Create an object.
- [DestroyObject](../../scripting/functions/DestroyObject.md): Destroy an object.
- [MoveObject](../../scripting/functions/MoveObject.md): Move an object.
| openmultiplayer/web/docs/translations/th/scripting/functions/CancelEdit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/CancelEdit.md",
"repo_id": "openmultiplayer",
"token_count": 505
} | 418 |
---
title: CreatePlayerTextDraw
description: Creates a textdraw for a single player.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Creates a textdraw for a single player. This can be used as a way around the global text-draw limit.
| Name | Description |
| -------- | ----------------------------------------------- |
| playerid | The ID of the player to create the textdraw for |
| Float:x | X-Coordinate |
| Float:y | Y-Coordinate |
| text[] | The text in the textdraw. |
## ส่งคืน
The ID of the created textdraw
## ตัวอย่าง
```c
// This variable is used to store the id of the textdraw
// so that we can use it throught the script
new PlayerText:welcomeText[MAX_PLAYERS];
public OnPlayerConnect(playerid)
{
// First, create the textdraw
welcomeText[playerid] = CreatePlayerTextDraw(playerid, 320.0, 240.0, "Welcome to my SA-MP server");
// Now show it
PlayerTextDrawShow(playerid, welcomeText[playerid]);
}
```
## บันทึก
:::tip
Player-textdraws are automatically destroyed when a player disconnects.
:::
:::warning
Keyboard key mapping codes (such as ~k~~VEHICLE_ENTER_EXIT~ Doesn't work beyond 255th character.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [PlayerTextDrawDestroy](../../scripting/functions/PlayerTextDrawDestroy.md): Destroy a player-textdraw.
- [PlayerTextDrawColor](../../scripting/functions/PlayerTextDrawColor.md): Set the color of the text in a player-textdraw.
- [PlayerTextDrawBoxColor](../../scripting/functions/PlayerTextDrawBoxColor.md): Set the color of a player-textdraw's box.
- [PlayerTextDrawBackgroundColor](../../scripting/functions/PlayerTextDrawBackgroundColor.md): Set the background color of a player-textdraw.
- [PlayerTextDrawAlignment](../../scripting/functions/PlayerTextDrawAlignment.md): Set the alignment of a player-textdraw.
- [PlayerTextDrawFont](../../scripting/functions/PlayerTextDrawFont.md): Set the font of a player-textdraw.
- [PlayerTextDrawLetterSize](../../scripting/functions/PlayerTextDrawLetterSize.md): Set the letter size of the text in a player-textdraw.
- [PlayerTextDrawTextSize](../../scripting/functions/PlayerTextDrawTextSize.md): Set the size of a player-textdraw box (or clickable area for PlayerTextDrawSetSelectable).
- [PlayerTextDrawSetOutline](../../scripting/functions/PlayerTextDrawSetOutline.md): Toggle the outline on a player-textdraw.
- [PlayerTextDrawSetShadow](../../scripting/functions/PlayerTextDrawSetShadow.md): Set the shadow on a player-textdraw.
- [PlayerTextDrawSetProportional](../../scripting/functions/PlayerTextDrawSetProportional.md): Scale the text spacing in a player-textdraw to a proportional ratio.
- [PlayerTextDrawUseBox](../../scripting/functions/PlayerTextDrawUseBox.md): Toggle the box on a player-textdraw.
- [PlayerTextDrawSetString](../../scripting/functions/PlayerTextDrawSetString.md): Set the text of a player-textdraw.
- [PlayerTextDrawShow](../../scripting/functions/PlayerTextDrawShow.md): Show a player-textdraw.
- [PlayerTextDrawHide](../../scripting/functions/PlayerTextDrawHide.md): Hide a player-textdraw.
| openmultiplayer/web/docs/translations/th/scripting/functions/CreatePlayerTextDraw.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/CreatePlayerTextDraw.md",
"repo_id": "openmultiplayer",
"token_count": 1144
} | 419 |
---
title: DisableNameTagLOS
description: Disables the nametag Line-Of-Sight checking so that players can see nametags through objects.
tags: []
---
## คำอธิบาย
Disables the nametag Line-Of-Sight checking so that players can see nametags through objects.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
public OnGameModeInit()
{
DisableNameTagLOS();
return 1;
}
```
## บันทึก
:::warning
This can not be reversed until the server restarts.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [ShowNameTags](../../scripting/functions/ShowNameTags.md): Set nametags on or off.
- [ShowPlayerNameTagForPlayer](../../scripting/functions/ShowPlayerNameTagForPlayer.md): Show or hide a nametag for a certain player.
| openmultiplayer/web/docs/translations/th/scripting/functions/DisableNameTagLOS.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/DisableNameTagLOS.md",
"repo_id": "openmultiplayer",
"token_count": 324
} | 420 |
---
title: GameModeExit
description: Ends the current gamemode.
tags: []
---
## คำอธิบาย
Ends the current gamemode.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
if (OneTeamHasWon)
{
GameModeExit();
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/GameModeExit.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GameModeExit.md",
"repo_id": "openmultiplayer",
"token_count": 171
} | 421 |
---
title: GetActorPos
description: Get the position of an actor.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Get the position of an actor.
| Name | Description |
| ------- | --------------------------------------------------------------------------------------- |
| actorid | The ID of the actor to get the position of. Returned by CreateActor. |
| X | A float variable, passed by reference, in which to store the X coordinate of the actor. |
| Y | A float variable, passed by reference, in which to store the Y coordinate of the actor. |
| Z | A float variable, passed by reference, in which to store the Z coordinate of the actor. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The actor specified does not exist.
The actor's position is stored in the specified variables.
## ตัวอย่าง
```c
new Float:x, Float:y, Float:z;
GetActorPos(actorid, x, y, z);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [SetActorPos](../functions/SetActorPos): Set the position of an actor.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetActorPos.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetActorPos.md",
"repo_id": "openmultiplayer",
"token_count": 602
} | 422 |
---
title: GetPVarString
description: Gets a player variable as a string.
tags: ["pvar"]
---
## คำอธิบาย
Gets a player variable as a string.
| Name | Description |
| -------------- | --------------------------------------------------------------------- |
| playerid | The ID of the player whose player variable to get. |
| varname | The name of the player variable, set by SetPVarString. |
| &string_return | The array in which to store the string value in, passed by reference. |
| len | The maximum length of the returned string. |
## ส่งคืน
The length of the string.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid,reason)
{
new playerName[MAX_PLAYER_NAME+1];
GetPlayerName(playerid, playerName, MAX_PLAYER_NAME);
SetPVarString(playerid, "PlayerName", playerName);
return 1;
}
public OnPlayerDeath(playerid, killerid, WEAPON:reason)
{
new playerName[MAX_PLAYER_NAME+1];
GetPVarString(playerid, "PlayerName", playerName, sizeof(playerName));
printf("%s died.", playerName);
}
```
## บันทึก
:::tip
If length of string is zero (value not set), string_return text will not be updated or set to anything and will remain with old data, neccesying that you clear the variable to blank value if GetPVarString returns 0 if that behavior is undesired
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPVarString: Set a string for a player variable.
- SetPVarInt: Set an integer for a player variable.
- GetPVarInt: Get the previously set integer from a player variable.
- SetPVarFloat: Set a float for a player variable.
- GetPVarFloat: Get the previously set float from a player variable.
- DeletePVar: Delete a player variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarString.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPVarString.md",
"repo_id": "openmultiplayer",
"token_count": 736
} | 423 |
---
title: GetPlayerCameraZoom
description: Retrieves the game camera zoom level for a given player.
tags: ["player"]
---
## คำอธิบาย
Retrieves the game camera zoom level for a given player.
| Name | Description |
| -------- | ----------------------------------------------------- |
| playerid | The ID of the player to get the camera zoom level of. |
## ส่งคืน
The player's camera zoom level (camera, sniper etc.), a float.
## ตัวอย่าง
```c
new szString[144];
format(szString, sizeof(szString), "Your camera zoom level: %f", GetPlayerCameraZoom(playerid));
SendClientMessage(playerid, -1, szString);
```
## บันทึก
:::tip
This retrieves the zoom level of the GAME camera, not the camera WEAPON.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerCameraAspectRatio](../functions/GetPlayerCameraAspectRation): Get the aspect ratio of a player's camera.
- [GetPlayerCameraPos](../functions/GetPlayerCameraPos): Find out where the player's camera is.
- [GetPlayerCameraFrontVector](../functions/GetPlayerCameraFrontVector): Get the player's camera front vector
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraZoom.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerCameraZoom.md",
"repo_id": "openmultiplayer",
"token_count": 449
} | 424 |
---
title: GetPlayerNetworkStats
description: Gets a player's network stats and saves them into a string.
tags: ["player"]
---
## คำอธิบาย
Gets a player's network stats and saves them into a string.
| Name | Description |
| ----------- | ------------------------------------------------------------- |
| playerid | The ID of the player you want to get the networkstats of. |
| retstr[] | The string to store the networkstats in, passed by reference. |
| retstr_size | The length of the string that should be stored. |
## ส่งคืน
This function always returns 1.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext, "/mynetstats"))
{
new stats[400+1];
GetPlayerNetworkStats(playerid, stats, sizeof(stats)); // get your own networkstats
ShowPlayerDialog(playerid, 0, DIALOG_STYLE_MSGBOX, "My NetworkStats", stats, "Okay", "");
}
return 1;
}
```
## บันทึก
:::tip
This function may not return accurate data when used under OnPlayerDisconnect if the player has quit normally. It usually returns accurate data if the player has been kicked or has timed out.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetNetworkStats: Gets the servers networkstats and saves it into a string.
- NetStats_GetConnectedTime: Get the time that a player has been connected for.
- NetStats_MessagesReceived: Get the number of network messages the server has received from the player.
- NetStats_BytesReceived: Get the amount of information (in bytes) that the server has received from the player.
- NetStats_MessagesSent: Get the number of network messages the server has sent to the player.
- NetStats_BytesSent: Get the amount of information (in bytes) that the server has sent to the player.
- NetStats_MessagesRecvPerSecond: Get the number of network messages the server has received from the player in the last second.
- NetStats_PacketLossPercent: Get a player's packet loss percent.
- NetStats_ConnectionStatus: Get a player's connection status.
- NetStats_GetIpPort: Get a player's IP and port.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerNetworkStats.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerNetworkStats.md",
"repo_id": "openmultiplayer",
"token_count": 752
} | 425 |
---
title: GetPlayerTime
description: Get the player's current game time.
tags: ["player"]
---
## คำอธิบาย
Get the player's current game time. Set by SetWorldTime, or by the game automatically if TogglePlayerClock is used.
| Name | Description |
| -------- | -------------------------------------------------------------- |
| playerid | The ID of the player to get the game time of. |
| &hour | A variable in which to store the hour, passed by reference. |
| &minute | A variable in which to store the minutes, passed by reference. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. The player specified does not exist.
The current game time is stored in the specified variables.
## ตัวอย่าง
```c
new hour, minutes;
GetPlayerTime(playerid, hour, minutes);
if (hour == 13 && minutes == 37)
{
SendClientMessage(playerid, COLOR_WHITE, "The time is 13:37!");
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerTime: Set a player's time.
- SetWorldTime: Set the global server time.
- TogglePlayerClock: Toggle the clock in the top-right corner.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerTime.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetPlayerTime.md",
"repo_id": "openmultiplayer",
"token_count": 463
} | 426 |
---
title: GetServerTickRate
description: Gets the tick rate (like FPS) of the server.
tags: []
---
## คำอธิบาย
Gets the tick rate (like FPS) of the server.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
printf("The current server tick rate is: %i", GetServerTickRate());
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetNetworkStats: Gets the servers networkstats and saves it into a string.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetServerTickRate.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetServerTickRate.md",
"repo_id": "openmultiplayer",
"token_count": 200
} | 427 |
---
title: GetVehiclePoolSize
description: Gets the highest vehicleid currently in use on the server.
tags: ["vehicle"]
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Gets the highest vehicleid currently in use on the server.
| Name | Description |
| ---- | ----------- |
## ตัวอย่าง
```c
RepairAllVehicles()
{
for(new i = 1, j = GetVehiclePoolSize(); i <= j; i++) // vehicleids start at 1
{
RepairVehicle(i);
}
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerPoolSize: Gets the highest playerid connected to the server.
| openmultiplayer/web/docs/translations/th/scripting/functions/GetVehiclePoolSize.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/GetVehiclePoolSize.md",
"repo_id": "openmultiplayer",
"token_count": 384
} | 428 |
---
title: IsObjectMoving
description: Checks if the given objectid is moving.
tags: []
---
## คำอธิบาย
Checks if the given objectid is moving.
| Name | Description |
| -------- | -------------------------------------------- |
| objectid | The objectid you want to check if is moving. |
## ส่งคืน
1 if the object is moving, 0 if not.
## ตัวอย่าง
```c
if (IsObjectMoving(objectid))
{
StopObject(objectid);
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [MoveObject](../../scripting/functions/MoveObject.md): Move an object.
- [StopObject](../../scripting/functions/StopObject.md): Stop an object from moving.
- [OnObjectMoved](../../scripting/callbacks/OnObjectMoved.md): Called when an object stops moving.
| openmultiplayer/web/docs/translations/th/scripting/functions/IsObjectMoving.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsObjectMoving.md",
"repo_id": "openmultiplayer",
"token_count": 338
} | 429 |
---
title: IsValidPlayerObject
description: Checks if the given object ID is valid for the given player.
tags: ["player"]
---
## คำอธิบาย
Checks if the given object ID is valid for the given player.
| Name | Description |
| -------- | ----------------------------------------------------- |
| playerid | The ID of the player whose player-object to validate. |
| objectid | The ID of the object to validate. |
## ส่งคืน
1 if the object exists, 0 if not.
## ตัวอย่าง
```c
// Check if an object is valid (exists) before we delete it
if (IsValidPlayerObject(playerid, objectid))
{
DestroyPlayerObject(playerid, objectid);
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CreatePlayerObject](../../scripting/functions/CreatePlayerObject.md): Create an object for only one player.
- [DestroyPlayerObject](../../scripting/functions/DestroyPlayerObject.md): Destroy a player object.
- [MovePlayerObject](../../scripting/functions/MovePlayerObject.md): Move a player object.
- [StopPlayerObject](../../scripting/functions/StopPlayerObject.md): Stop a player object from moving.
- [SetPlayerObjectPos](../../scripting/functions/SetPlayerObjectPos.md): Set the position of a player object.
- [SetPlayerObjectRot](../../scripting/functions/SetPlayerObjectRot.md): Set the rotation of a player object.
- [GetPlayerObjectPos](../../scripting/functions/GetPlayerObjectPos.md): Locate 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 an 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/IsValidPlayerObject.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/IsValidPlayerObject.md",
"repo_id": "openmultiplayer",
"token_count": 869
} | 430 |
---
title: NetStats_MessagesRecvPerSecond
description: Gets the number of messages the player has received in the last second.
tags: []
---
## คำอธิบาย
Gets the number of messages the player has received in the last second.
| Name | Description |
| -------- | ------------------------------------------ |
| playerid | The ID of the player to get the data from. |
## ส่งคืน
the number of messages the player has received in the last second.
## ตัวอย่าง
```c
public OnPlayerCommandText(playerid,cmdtext[])
{
if (!strcmp(cmdtext, "/msgpersec"))
{
new szString[144];
format(szString, sizeof(szString), "You have received %i network messages in the last second.", NetStats_MessagesRecvPerSecond(playerid));
SendClientMessage(playerid, -1, szString);
}
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerNetworkStats](../functions/GetPlayerNetworkStats.md): Gets a player networkstats and saves it into a string.
- [GetNetworkStats](../functions/GetNetworkStats.md): Gets the servers networkstats and saves it into a string.
- [NetStats_GetConnectedTime](../functions/NetStats_GetConnectedTime.md): Get the time that a player has been connected for.
- [NetStats_MessagesReceived](../functions/NetStats_MessagesReceived.md): Get the number of network messages the server has received from the player.
- [NetStats_BytesReceived](../functions/NetStats_BytesReceived.md): Get the amount of information (in bytes) that the server has received from the player.
- [NetStats_MessagesSent](../functions/NetStats_MessagesSent.md): Get the number of network messages the server has sent to the player.
- [NetStats_BytesSent](../functions/NetStats_BytesSent.md): Get the amount of information (in bytes) that the server has sent to the player.
- [NetStats_PacketLossPercent](../functions/NetStats_PacketLossPercent.md): Get a player's packet loss percent.
- [NetStats_ConnectionStatus](../functions/NetStats_ConnectionStatus.md): Get a player's connection status.
- [NetStats_GetIpPort](../functions/NetStats_GetIpPort.md): Get a player's IP and port.
| openmultiplayer/web/docs/translations/th/scripting/functions/NetStats_MessagesRecvPerSecond.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/NetStats_MessagesRecvPerSecond.md",
"repo_id": "openmultiplayer",
"token_count": 737
} | 431 |
---
title: PlayerTextDrawSetOutline
description: Set the outline of a player-textdraw.
tags: ["player", "textdraw", "playertextdraw"]
---
## คำอธิบาย
Set the outline of a player-textdraw. The outline colour cannot be changed unless PlayerTextDrawBackgroundColor is used.
| Name | Description |
| -------- | ---------------------------------------------------------------- |
| playerid | The ID of the player whose player-textdraw to set the outline of |
| text | The ID of the player-textdraw to set the outline of |
| size | The thickness of the outline. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
MyTextDraw = CreatePlayerTextDraw(playerid, 100.0, 33.0,"Example TextDraw");
PlayerTextDrawSetOutline(playerid, MyTextDraw, 1);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- 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.
- PlayerTextDrawTextSize: Set the size of a player-textdraw box (or clickable area for PlayerTextDrawSetSelectable).
- 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/PlayerTextDrawSetOutline.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/PlayerTextDrawSetOutline.md",
"repo_id": "openmultiplayer",
"token_count": 698
} | 432 |
---
title: RemoveVehicleComponent
description: Remove a component from a vehicle.
tags: ["vehicle"]
---
## คำอธิบาย
Remove a component from a vehicle.
| Name | Description |
| ----------- | ------------------------------ |
| vehicleid | ID of the vehicle. |
| componentid | ID of the component to remove. |
## ส่งคืน
0 - The component was not removed because the vehicle does not exist.
1 - The component was successfully removed from the vehicle.
## ตัวอย่าง
```c
//remove Nitro from vehicle number 1
RemoveVehicleComponent(1,1010);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [AddVehicleComponent](../functions/AddVehicleComponent.md): Add a component to a vehicle.
- [GetVehicleComponentInSlot](../functions/GetVehicleComponentInSlot.md): Check what components a vehicle has.
- [GetVehicleComponentType](../functions/GetVehicleComponentType.md): Check the type of component via the ID.
- [OnVehicleMod](../callbacks/OnVehicleMod.md): Called when a vehicle is modded.
- [OnEnterExitModShop](../callbacks/OnEnterExitModShop.md): Called when a vehicle enters or exits a mod shop.
| openmultiplayer/web/docs/translations/th/scripting/functions/RemoveVehicleComponent.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/RemoveVehicleComponent.md",
"repo_id": "openmultiplayer",
"token_count": 429
} | 433 |
---
title: SetActorInvulnerable
description: Toggle an actor's invulnerability.
tags: []
---
:::warning
ฟังก์ชั่นนี้ถูกเพิ่มใน SA-MP 0.3.7 และจะไม่ทำงานในเวอร์ชั่นก่อนหน้านี้!
:::
## คำอธิบาย
Toggle an actor's invulnerability.
| Name | Description |
| ------------ | ------------------------------------------------------- |
| actorid | The ID of the actor to set invulnerability. |
| invulnerable | 0 to make them vulnerable, 1 to make them invulnerable. |
## ส่งคืน
1 - Success
0 - Failure (i.e. Actor is not created).
## ตัวอย่าง
```c
new MyActor;
public OnGameModeInit()
{
MyActor = CreateActor(179, 316.1, -134.0, 999.6, 90.0); // Actor as a salesperson in Ammunation.
SetActorInvulnerable(MyActor, true);
return 1;
}
```
## บันทึก
:::warning
Once set invulnerable, the actor does not call OnPlayerGiveDamageActor. Players will have actor's invulnerability state changed only when it is restreamed to them.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
| openmultiplayer/web/docs/translations/th/scripting/functions/SetActorInvulnerable.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetActorInvulnerable.md",
"repo_id": "openmultiplayer",
"token_count": 568
} | 434 |
---
title: SetPVarInt
description: Set an integer player variable.
tags: ["pvar"]
---
## คำอธิบาย
Set an integer player variable.
| Name | Description |
| --------- | ------------------------------------------------------- |
| playerid | The ID of the player whose player variable will be set. |
| varname | The name of the player variable. |
| int_value | The integer to be set. |
## ส่งคืน
1: The function was executed successfully.
0: The function failed to execute. Either the player specified is not connected, or the variable name is null or over 40 characters.
## ตัวอย่าง
```c
// set GetPlayerMoney the value of player variable named "Money"
SetPVarInt(playerid, "Money", GetPlayerMoney(playerid));
// will print money that player has
printf("money: %d", GetPVarInt(playerid, "Money"));
```
## บันทึก
:::tip
Variables aren't reset until after OnPlayerDisconnect is called, so the values are still accessible in OnPlayerDisconnect.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPVarInt: Get the previously set integer from a player variable.
- SetPVarString: Set a string for a player variable.
- GetPVarString: Get the previously set string from a player variable.
- SetPVarFloat: Set a float for a player variable.
- GetPVarFloat: Get the previously set float from a player variable.
- DeletePVar: Delete a player variable.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarInt.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPVarInt.md",
"repo_id": "openmultiplayer",
"token_count": 567
} | 435 |
---
title: SetPlayerInterior
description: Set a player's interior.
tags: ["player"]
---
## คำอธิบาย
Set a player's interior. A list of currently known interiors and their positions can be found here.
| Name | Description |
| ---------- | -------------------------------------------------------------------- |
| playerid | The ID of the player to set the interior of. |
| interiorid | The [interior ID](../resources/interiorids.md) to set the player in. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player is not connected.
## ตัวอย่าง
```c
// Set player to default interior (outside)
SetPlayerInterior(playerid, 0);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerInterior: Get the current interior of a player.
- LinkVehicleToInterior: Change the interior that a vehicle is seen in.
- OnPlayerInteriorChange: Called when a player changes interior.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerInterior.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerInterior.md",
"repo_id": "openmultiplayer",
"token_count": 413
} | 436 |
---
title: SetPlayerSpecialAction
description: This function allows to set players special action.
tags: ["player"]
---
## คำอธิบาย
This function allows to set players special action.
| Name | Description |
| -------- | ---------------------------------------------------------------------- |
| playerid | The player that should perform the action |
| actionid | The [action](../resources/specialactions.md) that should be performed. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the player is not connected.
## ตัวอย่าง
```c
if (strcmp(cmd, "/handsup", true) == 0)
{
SetPlayerSpecialAction(playerid,SPECIAL_ACTION_HANDSUP);
return 1;
}
```
## บันทึก
:::tip
Removing jetpacks from players by setting their special action to 0 causes the sound to stay until death.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetPlayerSpecialAction: Get a player's current special action.
- ApplyAnimation: Apply an animation to a player.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerSpecialAction.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetPlayerSpecialAction.md",
"repo_id": "openmultiplayer",
"token_count": 453
} | 437 |
---
title: SetVehicleHealth
description: Set a vehicle's health.
tags: ["vehicle"]
---
## คำอธิบาย
Set a vehicle's health. When a vehicle's health decreases the engine will produce smoke, and finally fire when it decreases to less than 250 (25%).
| Name | Description |
| ------------ | ------------------------------------------- |
| vehicleid | The ID of the vehicle to set the health of. |
| Float:health | The health, given as a float value. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. This means the vehicle does not exist.
## ตัวอย่าง
```c
if (strcmp("/fixengine", cmdtext, true) == 0)
{
new vehicleid = GetPlayerVehicleID(playerid);
SetVehicleHealth(vehicleid, 1000);
SendClientMessage(playerid, COLOUR_WHITE, "The vehicles engine has been fully repaired.");
return 1;
}
```
## บันทึก
:::tip
Full vehicle health is 1000. Higher values are possible. For more information on health values, see this page.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- GetVehicleHealth: Check the health of a vehicle.
- RepairVehicle: Fully repair a vehicle.
- SetPlayerHealth: Set a player's health.
- OnVehicleDeath: Called when a vehicle is destroyed.
| openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleHealth.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/SetVehicleHealth.md",
"repo_id": "openmultiplayer",
"token_count": 493
} | 438 |
---
title: ShowPlayerMarkers
description: Toggles player markers (blips on the radar).
tags: ["player"]
---
## คำอธิบาย
Toggles player markers (blips on the radar). Must be used when the server starts (OnGameModeInit). For other times, see SetPlayerMarkerForPlayer.
| Name | Description |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------- |
| mode | The [mode](#marker-modes) to use for markers. They can be streamed, meaning they are only visible to nearby players. See table below. |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
public OnGameModeInit()
{
// Player markers only visible to nearby players
ShowPlayerMarkers(PLAYER_MARKERS_MODE_STREAMED);
}
```
## Marker Modes
| ID | MODE |
| --- | ---------------------------- |
| 0 | PLAYER_MARKERS_MODE_OFF |
| 1 | PLAYER_MARKERS_MODE_GLOBAL |
| 2 | PLAYER_MARKERS_MODE_STREAMED |
## บันทึก
:::tip
It is also possible to set a player's color to a color that has full transparency (no alpha value). This makes it possible to show markers on a per-player basis.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- SetPlayerMarkerForPlayer: Set a player's marker.
- LimitPlayerMarkerRadius: Limit the player marker radius.
- ShowNameTags: Set nametags on or off.
- SetPlayerColor: Set a player's color.
| openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerMarkers.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/ShowPlayerMarkers.md",
"repo_id": "openmultiplayer",
"token_count": 648
} | 439 |
---
title: TextDrawHideForAll
description: Hides a text draw for all players.
tags: ["textdraw"]
---
## คำอธิบาย
Hides a text draw for all players.
| Name | Description |
| ---- | ------------------------------------------------------------ |
| text | The ID of the textdraw to hide (returned by TextDrawCreate). |
## ส่งคืน
This function does not return any specific values.
## ตัวอย่าง
```c
new TextID;
TextID = TextDrawCreate(...);
//Later on
TextDrawShowForAll(TextID);
//Even later on
TextDrawHideForAll(TextID);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [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.
| openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawHideForAll.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TextDrawHideForAll.md",
"repo_id": "openmultiplayer",
"token_count": 393
} | 440 |
---
title: TogglePlayerClock
description: Toggle the in-game clock (top-right corner) for a specific player.
tags: ["player"]
---
## คำอธิบาย
Toggle the in-game clock (top-right corner) for a specific player. When this is enabled, time will progress at 1 minute per second. Weather will also interpolate (slowly change over time) when set using SetWeather/SetPlayerWeather.
| Name | Description |
| -------- | ------------------------------------------------- |
| playerid | The player whose clock you want to enable/disable |
| toggle | 1 to show and 0 to hide. Hidden by default. |
## ส่งคืน
1: The function executed successfully.
0: The function failed to execute. The specified player does not exist.
## ตัวอย่าง
```c
public OnPlayerConnect(playerid)
{
TogglePlayerClock(playerid, 1); // Show the clock
return 1;
}
```
## บันทึก
:::tip
Time will automatically advance 6 hours when the player dies.
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [GetPlayerTime](../functions/GetPlayerTime.md): Get the time of a player.
- [SetPlayerTime](../functions/SetPlayerTime.md): Set a player's time.
- [SetWorldTime](../functions/SetWorldTime.md): Set the global server time.
| openmultiplayer/web/docs/translations/th/scripting/functions/TogglePlayerClock.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/TogglePlayerClock.md",
"repo_id": "openmultiplayer",
"token_count": 480
} | 441 |
---
title: deleteproperty
description: Delete an earlier set property (setproperty).
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Delete an earlier set property (setproperty).
| Name | Description |
| ------ | ------------------------------------------------------------------------------ |
| id | The virtual machine to use. You should keep this as zero. |
| name[] | The property's name, you should keep this blank (""). |
| value | The property's unique ID. Use the hash-function to calculate it from a string. |
## ส่งคืน
The value of the property. If the property does not exist, the function returns 0.
## ตัวอย่าง
```c
deleteproperty(0, "", 123984334);
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [Setproperty](../../scripting/functions/Setproperty.md): Set a property.
- [Getproperty](../../scripting/functions/Getproperty.md): Get the value of a property.
- [Existproperty](../../scripting/functions/Existproperty.md): Check if a property exists.
| openmultiplayer/web/docs/translations/th/scripting/functions/deleteproperty.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/deleteproperty.md",
"repo_id": "openmultiplayer",
"token_count": 481
} | 442 |
---
title: floatmul
description: Multiplies two floats with each other.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
Multiplies two floats with each other.
| Name | Description |
| ----- | ------------------------------------------------- |
| oper1 | First Float. |
| oper2 | Second Float, the first one gets multiplied with. |
## ส่งคืน
The product of the two given floats
## ตัวอย่าง
```c
public OnGameModeInit()
{
new Float:Number1 = 2.3, Float:Number2 = 3.5; //Declares two floats, Number1 (2.3) and Number2 (3.5)
new Float:Product;
Product = floatmul(Number1, Number2); //Saves the product(=2.3*3.5 = 8.05) of Number1 and Number2 in the float "Product"
return 1;
}
```
## บันทึก
:::tip
This function is rather redundant, for it is no different than the conventional multiplication operator (\*).
:::
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [Floatadd](../functions/Floatadd): Adds two floats.
- [Floatsub](../functions/Floatsub): Subtracts two floats.
- [Floatdiv](../functions/Floatdiv): Divides a float by another.
| openmultiplayer/web/docs/translations/th/scripting/functions/floatmul.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/floatmul.md",
"repo_id": "openmultiplayer",
"token_count": 530
} | 443 |
---
title: funcidx
description: This function returns the ID of a public function by its name.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function returns the ID of a public function by its name.
| Name | Description |
| ------------ | ------------------------------------------------- |
| const name[] | The name of the public function to get the ID of. |
## ส่งคืน
The ID of the function (IDs start at 0). -1 if the function doesn't exist.
## ตัวอย่าง
```c
public OnFilterScriptInit()
{
printf("ID of OnFilterScriptInit: %d", funcidx("OnFilterScriptInit"));
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [CallLocalFunction](../functions/CallLocalFunction): Call a function in the script.
- [CallRemoteFunction](../functions/CallRemoteFunction): Call a function in any loaded script.
| openmultiplayer/web/docs/translations/th/scripting/functions/funcidx.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/funcidx.md",
"repo_id": "openmultiplayer",
"token_count": 375
} | 444 |
---
title: toupper
description: This function changes a single character to uppercase.
tags: []
---
:::warning
This function starts with lowercase letter.
:::
## คำอธิบาย
This function changes a single character to uppercase.
| Name | Description |
| ---- | ------------------------------------- |
| c | The character to change to uppercase. |
## ส่งคืน
The ASCII value of the character provided, but in uppercase.
## ตัวอย่าง
```c
public OnPlayerText(playerid, text[])
{
text[0] = toupper(text[0]);
//This sets the first character to upper case.
return 1;
}
```
## ฟังก์ชั่นที่เกี่ยวข้องกัน
- [tolower](../functions/tolower.md)
| openmultiplayer/web/docs/translations/th/scripting/functions/toupper.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/functions/toupper.md",
"repo_id": "openmultiplayer",
"token_count": 321
} | 445 |
---
title: Camera Cut Styles
---
## คำอธิบาย
Camera Cut Styles to be used with [SetPlayerCameraLookAt](../functions/SetPlayerCameraLookAt), [InterpolateCameraPos](../functions/InterpolateCameraPos.md) and [InterpolateCameraLookAt](../functions/InterpolateCameraLookAt.md).
## Cut Styles
```c
1 - CAMERA_MOVE
2 - CAMERA_CUT
```
| openmultiplayer/web/docs/translations/th/scripting/resources/cameracutstyles.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/cameracutstyles.md",
"repo_id": "openmultiplayer",
"token_count": 126
} | 446 |
---
title: Hex Colors
description: This deals with the color representation in hexadecimal in SAMP.
sidebar_label: Hex Colors
---
## What is hex?
The hexadecimal numeral system, or commonly known just as Hex, is a numeral system made up of 16 unique symbols (this is also known as base 16). You're probably wondering how this numeral system can have 16 symbols when our beloved decimal system (base 10) only has 10 symbols (0-9). Well the answer is quiet simple, let's take a look at both systems:
### Decimal (base 10)
```c
01
2
3
4
5
6
7
8
9
```
### Hexadecimal (base 16)
```c
01
2
3
4
5
6
7
8
9
A //10
B //11
C //12
D //13
E //14
F //15
```
Since there are no more available numbers, hex uses letters from the alphabet. Don't be scared by this, you can simply view them as place holders who's value is +1 of the previous number. This sounds very confusing and may even look pretty scary, but you will get used to it in no time at all.
Now let's take a look a few bigger numbers.
### Decimal (base 10)
```c
255
```
### Hexadecimal (base 16)
```c
FF
```
The number 255 is pretty understandable, but what is 'FF'? Let's take a look at both in their exponential notation.
:::caution **Note** | '^' is to the power of in this case, not the bitwise exclusive operator. :::
### Decimal (base 10)
```c
2 * (10^2) + 5 * (10^1) + 5 * (10^0)
//which equals
200+50+5
//which equals
255
```
Hex is exactly the same! The only difference is that it works with powers of 16 (Hence the base 10/16).
### Hexadecimal (base 16)
```c
F * (16^1) + F * (16^0)
//which equals
15 * (16^1) + 15 * (16^0)
//which equals
240+15
```
## When and how to use hex.
There isn't really a sole use for hex, you can use it when ever you want; though it's mostly used for color defines (We'll take a look at this later). Some people use hex as a visual aid to make things look more clearly (Y_Less) for example:
:::caution **Note** | This is a complicated example, don't worry if you don't understand it. :::
```c
var = b & 0x04
```
That makes it very clear that I want the 4 high bits of the low byte of b, on the other hand:
```c
var = b & 4
```
Isn't very friendly to the eyes at all.
Notice how '04' has '0x' in front of it. This is a constant symbol in pawn that allows the use of hexadecimal (like 0b is for binary).
## Hex colors
Hex colors follow this format:
```c
RR - Two values for the red (Where FF is max, and 00 is the lowest).
GG - Two values for the green (Where FF is max, and 00 is the lowest).
BB - Two values for the blue (Where FF is max, and 00 is the lowest).
AA - Two values for the transparency (Where FF is max, and 00 is the lowest).
```
Let's take a look at a few colors, starting with the basics and moving into the combinations.
```c
//basics
0x00000000 - Black
0xFF0000FF - Bright red.
0x00FF00FF - Bright green.
0x0000FFFF - Bright blue.
0xFFFFFFFF - White
//combinations
0xFFFF00FF - Bright yellow
0xFF00FFFF - Bright purple
0x00FFFFFF - Bright cyan
```
These are just the basic colors/combination, if you're looking for other colors / are too lazy to convert, you are better using a converter like this one:
| openmultiplayer/web/docs/translations/th/scripting/resources/hexcolors.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/hexcolors.md",
"repo_id": "openmultiplayer",
"token_count": 1015
} | 447 |
---
title: "Pvar Types"
---
Types of player variables, to be used in [Per-player variable system.](../tutorials/perplayervariablesystem)
```c
PLAYER_VARTYPE_NONE (0)
PLAYER_VARTYPE_INT (1)
PLAYER_VARTYPE_STRING (2)
PLAYER_VARTYPE_FLOAT (3)
```
| openmultiplayer/web/docs/translations/th/scripting/resources/pvartypes.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/th/scripting/resources/pvartypes.md",
"repo_id": "openmultiplayer",
"token_count": 113
} | 448 |
---
title: Ortak İstemci Sorunları
---
### "San Andreas cannot be found" hatası alıyorum
San Andreas Multiplayer, **bağımsız bir program değildir!** San Andreas'a çok oyunculu işlevsellik ekler ve bu nedenle PC için GTA San Andreas'a ihtiyacınız vardır - ayrıca GTA sürümü **ABD/AB v1.0** olması gerekir; diğer sürümler, v2.0 veya Steam ve Direct2Drive sürümleri çalışmaz. [GTA: SA sürümünüzü 1.0'a düşürmek için buraya tıklayın](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661).
### SA:MP tarayıcısında hiç sunucu göremiyorum
SA:MP tarayıcısı artık çalışmıyor. Yeni [open.mp istemcisini indirin](https://github.com/openmultiplayer/launcher/releases/latest).
Hâlâ sunucuları göremiyorsanız, open.mp'ye güvenli erişim izni vermelisiniz. Maalesef, mevcut birçok güvenlik duvarı yazılımı nedeniyle buna daha fazla destek sunamıyoruz - üreticinin web sitesine bakmanızı veya Google'da bir arama yapmanızı öneririz. Ayrıca, en son çıkan open.mp sürümüne sahip olduğunuzdan emin olun!
### SA:MP yerine Singleplayer GTA Yükleniyor
:::warning
Tek oyunculu seçeneklerini (yeni oyun, oyun yükle, vb.) görmemeniz gerekiyor - SA:MP kendi başına yüklenmeli ve bu seçenekleri görmemeniz gerekiyor. Eğer "yeni oyun" görüyorsanız, tek oyunculu yüklendi demektir, San Andreas Multiplayer değil.
:::
Tek oyunculu, SA:MP'yi yanlış bir klasöre kurduysanız veya yanlış bir San Andreas sürümüne sahipseniz yüklenir. Yanlış bir sürüme sahipseniz, GTA San Andreas sürüm düşürücüsünü kullanarak oyununuzun sürümünü düşürebilirsiniz. İndirmek için [buraya tıklayın](http://grandtheftauto.filefront.com/file/GTA_SA_Downgrader_Patch;74661).
Bazen tek oyunculu menü görünebilir, ancak aslında SA:MP düzgün bir şekilde yüklenmiştir. Bu durumu düzeltmek için menüde bir öğe seçmeniz ve ardından çıkış tuşuna basmanız yeterlidir. SA:MP ardından yüklenmeye devam eder.
### Bir sunucuya bağlanırken "Unacceptable Nickname" hatası alıyorum
Adınızda (0-9, a-z, \[\], (), \$, @, ., \_ ve = kullanın) yasaklanmış karakterleri kullanmadığınızdan ve adınızın 20 karakterden uzun olmadığından emin olun. Ayrıca, bir oyuncu sizinle aynı isimde girmeye çalıştığınız sunucuda olabilir (bu, zaman aşımından veya çökmeden hemen sonra hızlı bir şekilde sunucuya yeniden bağlandığınızda olabilir). 50 günden fazla süredir çalışan bir Windows sunucusu bazen bu hataya neden olabilir.
### Ekranda "Connecting to IP:Port..." takılı kalıyor
Sunucu çevrimdışı olabilir veya hiçbir sunucuya bağlanamıyorsanız, güvenlik duvarınızı devre dışı bırakın ve çalışıp çalışmadığını kontrol edin. Çalışıyorsa, güvenlik duvarınızı yeniden yapılandırmanız gerekebilir. Ayrıca, eski bir SA:MP sürümünü çalıştırıyorsanız, yeni sürümleri [buradan](https://sa-mp.mp/downloads/) bulabilirsiniz.
### Modlu GTA: San Andreas'a sahibim ve SA:MP yüklenmiyor
Yüklenmiyorsa modlarınızı kaldırın.
### SA:MP yüklenmiş GTA'yı başlatınca çalışmıyor
Kullanıcı dosyanızdaki gta_sa.set dosyasını silin ve herhangi bir hile/modunuz olmadığından emin olun.
### Araç patladığında oyun çöküyor
Eğer 2 monitörünüz varsa, bunu çözmenin 3 yolu vardır:
1. Sa-mp oynarken 2. monitörünüzü devre dışı bırakın. (Eğer monitörü açık tutmak istiyorsanız belki de pek akıllıca değil.)
2. Görüntü FX kalitesinizi düşük yapın. (Esc > Settings > Display Setuo > Advanced)
3. GTA San Andreas klasörünüzü yeniden adlandırın (örneğin "GTA San Andreas2") (Bu genellikle işe yarar, ancak bazen tekrar çalışmayı durdurabilir, bu nedenle başka bir şeye yeniden adlandırmanız gerekir.)
### Pause menüsünden çıktıktan sonra farem çalışmıyor
Eğer fare oyun içinde donmuş gibi görünüyorsa (kısmen) ve pause menüsünde çalışıyorsa, [sa-mp.cfg](ClientCommands#file-sa-mpcfg "Sa-mp.cfg") dosyasındaki multicore seçeneğini devre dışı bırakmalısınız (0 olarak ayarlayın). Fare tekrar yanıt verene kadar sürekli Escape tuşuna basmak da işe yarayabilir, ancak bu düzgün bir çözüm değildir.
### dinput8.dll dosyası eksik
Bu, DirectX düzgün yüklenmediğinde ortaya çıkabilir, tekrar yüklemeyi deneyin - PC'nizi yeniden başlatmayı unutmayın. Sorun hala devam ederse, C:\\Windows\\System32 dizinine gidin ve dinput.dll dosyasını GTA San Andreas'ın ana dizinine kopyalayın. Bu sorunu çözecektir.
### Diğer oyuncuların adlarını göremiyorum!
Lütfen bazı sunucuların takma adları genel olarak devre dışı bıraktığını unutmayın. Aksi takdirde, bu sorun genellikle Intel HD entegre grafik işlemcileri olan bilgisayarlarda ortaya çıkar (ki zaten oyun oynamak için tasarlanmamışlar). Maalesef, kesin neden bilinmiyor ve şu anda genel bir çözüm bulunmuyor. Uzun vadeli bir çözüm, mümkünse ve bütçeniz izin veriyorsa bilgisayarınıza grafik kartı takmaktır.
| openmultiplayer/web/docs/translations/tr/client/CommonClientIssues.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/client/CommonClientIssues.md",
"repo_id": "openmultiplayer",
"token_count": 2282
} | 449 |
---
title: OnObjectMoved
description: Bu callback obje hareket etmeyi (MoveObject) bıraktıktan sonra çağrılır.
tags: []
---
## Açıklama
Bu callback obje hareket etmeyi (MoveObject) bıraktıktan sonra çağrılır.
| Ad | Açıklama |
| -------- | -------------------- |
| objectid | Hareket eden obje id |
## Çalışınca Vereceği Sonuçlar
Her zaman öncelikle filterscriptler içerisinde çağrılır.
## Örnekler
```c
public OnObjectMoved(objectid)
{
printf("Obje id %d hareket etmeyi bıraktı.", objectid);
return 1;
}
```
## Notlar
:::tip
SetObjectPos bu callback içerisinde çalışmaz. Bunu düzeltmek için objeyi yeniden oluşturun.
:::
## Bağlı Fonksiyonlar
- [MoveObject](../functions/MoveObject.md): Objeyi hareket ettirme fonksiyonu.
- [MovePlayerObject](../functions/MovePlayerObject.md): Oyuncu objesini hareket ettirme fonksiyonu.
- [IsObjectMoving](../functions/IsObjectMoving.md): Objenin hareket edip etmediğini kontrol etme fonksiyonu.
- [StopObject](../functions/StopObject.md): Hareket eden objeyi durdurur.
- [OnPlayerObjectMoved](OnPlayerObjectMoved.md): Oyuncu objesi hareket etmeyi bıraktığında çağrılan callback.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnObjectMoved.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnObjectMoved.md",
"repo_id": "openmultiplayer",
"token_count": 507
} | 450 |
---
title: OnPlayerFinishedDownloading
description: Bu callback, bir oyuncu model cache indirmesini bitirdiğinde çağırılır.
tags: ["player"]
---
<VersionWarnTR name='callback' version='SA-MP 0.3.DL R1' />
## Açıklama
Bu callback, bir oyuncu model cache indirmesini bitirdiğinde çağırılır.
| İsim | Açıklama |
| ------------ | ------------------------------------------------------------------------------ |
| playerid | Model cacheini indirmeyi bitiren oyuncunun ID'si. |
| virtualworld | Oyuncunun model cache indirmesini bitirdiği virtual world ID'si. |
## Çalışınca Vereceği Sonuçlar
Bu callback herhangi bir geri döndürülen değer içermemekte.
## Örnekler
```c
public OnPlayerFinishedDownloading(playerid, virtualworld)
{
SendClientMessage(playerid, 0xffffffff, "İndirme tamamlandı.");
return 1;
}
```
## Notlar
:::tip
Bu callback oyuncu her virtual world değiştirdiğinde indireceği model olmasa bile çağırılır.
:::
## Bağlantılı Fonksiyonlar
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerFinishedDownloading.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerFinishedDownloading.md",
"repo_id": "openmultiplayer",
"token_count": 501
} | 451 |
---
title: OnPlayerStreamIn
description: Bu fonksiyon, bir oyuncu başka bir oyuncunun streamer bölgesinde yayınlandığında çağrılır.
tags: ["player"]
---
## Açıklama
Bu fonksiyon, bir oyuncu başka bir oyuncunun streamer bölgesinde yayınlandığında çağrılır.
| Parametre | Açıklama |
| ----------- | ------------------------------------------------------- |
| playerid | Diğer oyuncuya canlı olarak görülen oyuncu. |
| forplayerid | Diğer oyuncuyu canlı olarak gören oyuncu. |
## Çalışınca Vereceği Sonuçlar
Filterscript komutlarında her zaman ilk olarak çağrılır.
## Örnekler
```c
public OnPlayerStreamIn(playerid, forplayerid)
{
new string[40];
format(string, sizeof(string), "Oyuncu %d artık sizin için yayınlanıyor.", playerid);
SendClientMessage(forplayerid, 0xFFFFFFFF, string);
return 1;
}
```
## Notlar
<TipNPCCallbacks />
## Bağlantılı Fonksiyonlar
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStreamIn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnPlayerStreamIn.md",
"repo_id": "openmultiplayer",
"token_count": 467
} | 452 |
---
title: OnVehicleSpawn
description: Bu callback bir araç respawn edildiğinde çağrılır.
tags: ["vehicle"]
---
:::warning
Bu callback **sadece** araç **re**spawn edildiğinde çağrılır! CreateVehicle ve AddStaticVehicle(Ex) bu callbacki **tetiklemeyecektir**.
:::
## Açıklama
Bu callback bir araç respawn edildiğinde çağrılır.
| İsim | Açıklama |
| --------- | ----------------------------------- |
| vehicleid | Spawnlanan aracın ID'si. |
## Çalışınca Vereceği Sonuçlar
0 - Diğer filterscriptslerin bu callbacki çağırmasını önler.
1 - Bu callbackin sonraki filterscriptslerde pas geçileceğini gösterir.
Her zaman ilk filterscriptslerde çağrılır.
## Örnekler
```c
public OnVehicleSpawn(vehicleid)
{
printf("Araç %i spawnlandı!",vehicleid);
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [SetVehicleToRespawn](../functions/SetVehicleToRespawn): Aracı respawn eder.
- [CreateVehicle](../functions/CreateVehicle): Araç oluşturur.
| openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/callbacks/OnVehicleSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 448
} | 453 |
---
title: AllowNickNameCharacter
description: Bir karakterin takma adlarda kullanılmasına izin verir.
tags: []
---
<VersionWarnTR version='omp v1.1.0.2612' />
## Açıklama
Bir karakterin takma adlarda kullanılmasına izin verir.
| İsim | Açıklama |
| -------- | --------------------------------------- |
| character | İzin verilecek veya izin verilmeyecek karakter. |
| bool:allow | true - İzin ver, false - İzin verme |
## Çalışınca Vereceği Sonuçlar
Bu fonksiyon belirli bir değer döndürmez.
## Örnekler
```c
public OnGameModeInit()
{
AllowNickNameCharacter('*', true); // * karakterine izin ver
AllowNickNameCharacter('[', false); // [ karakterine izin verme
AllowNickNameCharacter(']', false); // ] karakterine izin verme
return 1;
}
```
## Bağlantılı Fonksiyonlar
- [IsValidNickName](IsValidNickName): Bir takma adın geçerli olup olmadığını kontrol eder.
- [SetPlayerName](SetPlayerName): Bir oyuncunun adını ayarlar.
- [GetPlayerName](GetPlayerName): Bir oyuncunun adını alır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/AllowNickNameCharacter.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/AllowNickNameCharacter.md",
"repo_id": "openmultiplayer",
"token_count": 466
} | 454 |
---
title: ChangeVehicleColor
description: Aracın birincil ve ikincil rengini değiştirme.
tags: ["vehicle"]
---
## Açıklama
Aracın birincil ve ikincil rengini değiştirme.
| Parametre | Açıklama |
| --------- | ---------------------------------------------- |
| vehicleid | Rengi değişecek aracın ID'si. |
| color1 | Değişecek birincil rengin ID'si. |
| color2 | Değişecek ikincil rengin ID'si. |
## Çalşınca Vereceği Sonuçlar
1: Fonksiyon başarılı, aracın rengi değiştirildi.
0: Fonksiyon başarısız, geçersiz araç ID'si.
## Örnekler
```c
public OnPlayerEnterVehicle(playerid, vehicleid, ispassenger)
{
// Oyuncu herhangi bir araca bindiğinde, aracın birincil rengi siyah ikincil rengi ise beyaz olacaktır.
ChangeVehicleColor(vehicleid, 0, 1);
return 1;
}
```
## Notlar
:::tip
Bazı araçlar tek renge sahiptir bu yüzden ikincil rengi olmadığı için değiştirilmez. Bazı araçlar ise (örn: cement, squallo) 4 renge sahiptir, bu 4 rengin ikisi değiştirilirken SA:MP desteklemediği için diğer ikisi değiştirilemez.
:::
## Bağlantılı Fonksiyonlar
- [ChangeVehiclePaintjob](ChangeVehiclePaintjob): Aracın kaplamasını değiştirme.
- [OnVehicleRespray](../callbacks/OnVehicleRespray): Bu fonksiyon araç respray noktasına girdiğinde çağrılır.
| openmultiplayer/web/docs/translations/tr/scripting/functions/ChangeVehicleColor.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/ChangeVehicleColor.md",
"repo_id": "openmultiplayer",
"token_count": 688
} | 455 |
---
title: GetActorVirtualWorld
description: Aktörün sanal dünya değerini kontrol etme.
tags: []
---
<VersionWarnTR version='SA-MP 0.3.7' />
## Açıklama
Aktörün sanal dünya değerini kontrol etme.
| Parametre | Açıklama |
| ------- | ------------------------------------------------ |
| actorid | Sanal dünya değeri kontrol edilecek aktör ID'si. |
## Çalışınca Vereceği Sonuçlar
Aktörün sanal dünyasını çeker. Varsayılan değer sıfırdır. Eğer aktör yoksa bile sanal dünya değerini sıfır olarak çeker.
## Örnekler
```c
new MyActor;
public OnGameModeInit()
{
MyActor = CreateActor(...); // Aktörü oluşturduk.
SetActorVirtualWorld(MyActor, 69); // Aktörümüzün sanal dünya değerini 69 yaptık.
return 1;
}
// Herhangi bir yere
if (GetActorVirtualWorld(MyActor) == 69) // Eğer aktörümüzün sanal dünya değeri 69'a eşitse...
{
// Birşey yap...
}
```
## Bağlantılı Fonksiyonlar
- [SetActorVirtualWorld](SetActorVirtualWorld): Aktörün sanal dünya değerini ayarlama.
| openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorVirtualWorld.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/tr/scripting/functions/GetActorVirtualWorld.md",
"repo_id": "openmultiplayer",
"token_count": 493
} | 456 |
---
title: Client
description: 此类别包含有关SA-MP客户端特性和支持的信息。
---
此类别包含有关SA-MP客户端特性和支持的信息。
| openmultiplayer/web/docs/translations/zh-cn/client/_.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/client/_.md",
"repo_id": "openmultiplayer",
"token_count": 102
} | 457 |
---
title: OnNPCEnterVehicle
description: 当NPC进入车辆时会调用此回调。
tags: []
---
## 描述
当 NPC 进入车辆时会调用此回调。
| 参数名 | 说明 |
| --------- | ----------------- |
| vehicleid | NPC 进入的车辆 ID |
| seatid | NPC 使用的座位 ID |
## 案例
```c
public OnNPCEnterVehicle(vehicleid, seatid)
{
printf("NPC进入了车辆ID: %d 座位ID: %d", vehicleid, seatid);
return 1;
}
```
## 相关回调
- [OnNPCExitVehicle](../callbacks/OnNPCExitVehicle): 当 NPC 离开车辆时被调用。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCEnterVehicle.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnNPCEnterVehicle.md",
"repo_id": "openmultiplayer",
"token_count": 318
} | 458 |
---
title: OnPlayerEnterCheckpoint
description: 当玩家进入为该玩家设置的检查点时,该回调被调用。
tags: ["player", "checkpoint"]
---
## 描述
当玩家进入为该玩家设置的检查点时,此回调将被调用。
| 参数名 | 描述 |
| -------- | ------------------ |
| playerid | 进入检查点的玩家。 |
## 返回值
它在过滤脚本中总是先被调用。
## 案例
```c
// 在这个案例中,玩家出生时为玩家创建了一个检查点
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;
}
```
## 要点
<TipNPCCallbacksCN />
## 相关函数
- [SetPlayerCheckpoint](../functions/SetPlayerCheckpoint): 为玩家创造一个检查点,。
- [DisablePlayerCheckpoint](../functions/DisablePlayerCheckpoint): 禁用玩家当前的检查点。
- [IsPlayerInCheckpoint](../functions/IsPlayerInRaceCheckpoint): 检查玩家是否处于检查点。
- [SetPlayerRaceCheckpoint](../functions/SetPlayerRaceCheckpoint): 为玩家创造一个比赛检查点。
- [DisablePlayerRaceCheckpoint](../functions/DisablePlayerRaceCheckpoint): 禁用玩家当前的比赛检查点。
- [IsPlayerInRaceCheckpoint](../functions/IsPlayerInRaceCheckpoint): 检查玩家是否处于比赛检查点。
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEnterCheckpoint.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerEnterCheckpoint.md",
"repo_id": "openmultiplayer",
"token_count": 844
} | 459 |
---
title: OnPlayerRequestSpawn
description: 当玩家通过按下SHIFT键或点击“重生”按钮来尝试通过类选择器进行重生时调用。
tags: ["player"]
---
## 描述
当玩家通过按下 SHIFT 键或点击“重生”按钮来尝试通过类选择器进行重生时调用。
| 参数名 | 描述 |
| -------- | --------------------- |
| playerid | 请求重生的玩家的 ID。 |
## 返回值
它总是在过滤脚本中首先被调用,因此在那里返回 0 也会阻止其他脚本看到它。
## 案例
```c
public OnPlayerRequestSpawn(playerid)
{
if (!IsPlayerAdmin(playerid))
{
SendClientMessage(playerid, -1, "你不能重生");
return 0;
}
return 1;
}
```
## 要点
<TipNPCCallbacksCN />
:::tip
为了防止玩家重生特定的类,最后查看的类必须保存在 OnPlayerRequestClass 的一个变量中。
:::
| openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerRequestSpawn.md/0 | {
"file_path": "openmultiplayer/web/docs/translations/zh-cn/scripting/callbacks/OnPlayerRequestSpawn.md",
"repo_id": "openmultiplayer",
"token_count": 537
} | 460 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.