Список скриптовых функций Team Fortress 2
You can help by finishing the translation.
Also, please make sure the article tries to comply with the alternate languages guide.
Этот список состоит из классов Squirrel движка, функции и переменные доступны для VScript в Team Fortress 2
Официальная документация может быть отображена в консоли, изменив developer
на любое значение выше нуля, загрузив карту, и введя script_help
. Однако, такая документация не перечисляет всё, заставляя находить остальное самостоятельно.
[Нужно сделать] ДОДЕЛАТЬ [Нужно сделать] |
---|
#1 Нужно сделать: Описание всех функцийDescriptions of every function.
|
#2 Нужно сделать: Скрипт отладка функций не имеет никакой другой информации, кроме как их имён!
|
#3 Нужно сделать: Consolidate script function subpages from together into a generic page that describes both and , including any differences both branches have. E.g. TraceLine , ClientPrint ...
|
Экземпляры
Имя | Класс | Описание |
---|---|---|
Convars
|
Convars
|
Интерфейс, позволяющий читать и записывать консольные переменные. |
Entities
|
CEntities
|
Предоставляет доступ к только что заспавненным энтити. |
EntityOutputs
|
CScriptEntityOutputs
|
Позволяет манипулировать выводом данных энтити. |
NavMesh
|
CNavMesh
|
Предостовляет доступ к NavMesh и NavAreas карты. |
NetProps
|
CNetPropManager
|
Позволяет читать и обновлять сетевые свойства энтити. |
PlayerVoiceListener
|
PlayerVoiceListener
|
Следит за игроками, которые используют голосовой чат и с какой продолжительностью. |
Переменные
Имя | Тип | Величина / Описание |
---|---|---|
__FILE__
|
string | Имя файла текущего выполняющегося скрипта |
__LINE__
|
integer | Номер текущей выполняющейся линии |
Constants
|
table | Нумерации различных аргументов функции или нетпропов. |
Documentqtion
|
table | Содержит выведенные строки из команды script_help .
|
GameEventCallbacks
|
table | Таблица зарегестрированных выводов игровых событий. |
print_indent
|
integer | 0. Пробелы для отступа при печати, за исключением пробелов из realPrint .
|
_PublishedHelp
|
table | NONE |
ScriptEventCallbacks
|
table | Таблица зарегестрированных выводов игровых скриптов. |
ScriptHookCallbacks
|
table | Таблица зарегестрированных выводов игровых хуков. |
Script Debug
Имя | Тип | Величина |
---|---|---|
ScriptDebugDefaultWatchColor
|
array | [0, 192, 0] |
ScriptDebugDrawTextEnabled
|
bool | true |
ScriptDebugDrawWatchesEnabled
|
bool | true |
ScriptDebugInDebugDraw
|
bool | false |
ScriptDebugText
|
array | NONE |
ScriptDebugTextIndent
|
integer | 0 |
ScriptDebugTextFilters
|
table | NONE |
ScriptDebugTraces
|
table | NONE |
ScriptDebugTraceAllOn
|
bool | false |
ScriptDebugWatches
|
array | NONE |
Константа
Константа — величина, которую нельзя заменить во время выпоьнения программы. Обычно используются для избавления от экземпляров магических цифр, задавая им самоописывающиеся имена.
Имя | Тип | Величина |
---|---|---|
_charsize_
|
integer | 1 |
_floatsize_
|
integer | 4 |
_intsize_
|
integer | 4 |
_version_
|
string | "Squirrel 3.2 stable" |
_versionnumber_
|
integer | 320 |
RAND_MAX
|
integer | 32767 |
PI
|
float | 3.14159 |
Перечисления
- Просмотрите эту страницу со всеми перечислениями под таблицей
Constants
.
Перечисления так же вписаны в таблицу Constants
. Каждое перечисление имеет свою константу. Например, чтобы добраться до константы HIDEHUD_CROSSHAIR
перечисления HideHUD
, нужно прописать Constants.HideHUD.HIDEHUD_CROSSHAIR
.
Классы
CBaseEntity
Это скрипт дескриптора класса. Все энтити имеют дискриптор, благодаря этому классу (иногда как один из подклассов).
Дескриптор энтити может быть доступен из:
- Экземпляра
энтити
. - Функции
EntIndexToHScript
. - Ключевое слово
self
(только для Entity Scripts ).
Методы
Функция | Запись | Описание |
---|---|---|
__KeyValueFromFloat (→ KeyValueFromFloat)
|
bool __KeyValueFromFloat(string key, float value)
|
Работает так же, как и KeyValueFromFloat , поэтому используйте это.
|
__KeyValueFromInt (→ KeyValueFromInt)
|
bool __KeyValueFromInt(string key, int value)
|
Работает так же, как и KeyValueFromInt , поэтому используйте это.
|
__KeyValueFromString (→ KeyValueFromString)
|
bool __KeyValueFromString(string key, string value)
|
Работает так же, как и KeyValueFromString , поэтому используйте это.
|
__KeyValueFromVector (→ KeyValueFromVector)
|
bool __KeyValueFromVector(string key, Vector value)
|
Работает так же, как и KeyValueFromVector , поэтому используйте это.
|
AddEFlags
|
void AddEFlags(int flags)
|
Добавляет к энтити предоставленные флаги к Энтити флагам. (m_iEFlags datamap)
Смотрите Constants.FEntityEFlags. |
AddFlag
|
void AddFlag(int flags)
|
Добавляет предоставленные флаги к другому отдельному игроку-энтити в систему флагов энтити. (m_fFlags datamap)
Смотрите Constants.FPlayer. |
AddSolidFlags
|
void AddSolidFlags(int flags)
|
Добавляет к энтити предоставленные флаги в Solid Flags. (m_Collision.m_usSolidFlags datamap)
Смотрите Constants.FSolid. |
ApplyAbsVelocityImpulse
|
void ApplyAbsVelocityImpulse(Vector impulse)
|
Приминяет Испульс Скорости в качестве импульса вектора мирового пространства. Работает почти для всех физических объектов, включая выброшенные оружия и даже брошеные Бутерброды. |
ApplyLocalAngularVelocityImpulse
|
void ApplyLocalAngularVelocityImpulse(Vector impulse)
|
Приминяет Импульс Угловой Скорости к локальному пространству энтити. Направление вектора ввода - ось поворота, длина - сила импульса. |
BecomeRagdollOnClient
|
bool BecomeRagdollOnClient(Vector impulse)
|
Работает как ввод BecomeRagdoll с требуемым значением импульса в качестве силы для регдола. НЕ спавнит prop_ragdoll или инное энтити.
|
ClearFlags
|
void ClearFlags()
|
Обнуляет каждый флаг игрока-энтити, что является их очисткой. |
ClearSolidFlags
|
void ClearSolidFlags()
|
Обнуляет каждый Solid Flags этити, что является их очисткой. |
ConnectOutput
|
void ConnectOutput(string output, string function)
|
Добавляет соединение Ввод/Вывод, которое вызывается именем функции, когда выбранный вывод срабатывает. |
Destroy
|
void Destroy()
|
Удаляет энтити. Просто называется UTIL Remove . |
DisableDraw
|
void DisableDraw()
|
Отключает отображение и отправку энтити клиентам. (добавляет EF_NODRAW) |
DisconnectOutput
|
void DisconnectOutput(string output, string function)
|
Удаляет подключенный скрипт функции из события Ввода/Вывода. |
DispatchSpawn
|
void DispatchSpawn()
|
Альтернативная отправка спавна, как в CEntities, для удобства.
Примечание:Применение метода на игроках зареспавнит их.
|
EmitSound
|
void EmitSound(string)
|
Проигрывает звук из этого энтити. |
EnableDraw
|
void EnableDraw()
|
Включает отображение и отправку этого энтити клиентам. (убирает EF_NODRAW) |
entindex
|
int entindex()
|
Возвращает индекс энтити. |
EyeAngles
|
QAngle EyeAngles()
|
Возвращает углы обзора энтити. Работает как GetAbsAngles , если энтити не поддерживает это.
|
EyePosition
|
Vector EyePosition()
|
Возвращает позицию глаз энтити. Работает как GetOrigin , если энтити не поддерживает это.
|
FirstMoveChild
|
handle FirstMoveChild()
|
Возвращает самый ранний дочерний энтити.
Совет:Пример использования:
for (local child = entity.FirstMoveChild(); child != null; child = child.NextMovePeer())
|
GetAbsAngles
|
QAngle GetAbsAngles()
|
Берёт все углы поворота энтити как QAngles. |
GetAbsVelocity
|
Vector GetAbsVelocity()
|
Возвращает текущий модуль скорости энтити. |
GetAngles (→ GetAbsAngles)
|
Vector GetAngles()
|
Берёт все углы поворота энтити как Vector. |
GetAngularVelocity
|
Vector GetAngularVelocity()
|
Берёт локальную угловую скорость - возвращает Vector угла поворота. |
GetBaseVelocity
|
Vector GetBaseVelocity()
|
Возвращает любую константу действующей скорости энтити. Так же включает в себя силу от эффектов, например, trigger_push, и игроков, стоящих на движующейся геометрии, например, лифты. Должно всегда возвращать нулевой вектор, если энтити не двигается от чего либо. |
GetBoundingMaxs
|
Vector GetBoundingMaxs()
|
Берёт вектор, имеющий максимальные границы, центрированный на объекте |
GetBoundingMaxsOriented
|
Vector GetBoundingMaxsOriented()
|
Берёт вектор, имеющий максимальные границы, центрированный на объекте, с учетом ориентации объекта
Баг:Функция не трансформирует границы правильно и, в некоторых случаях, границы не покроют всё энтити. В качесвте обхода, используйте неориентированные границы и примените ААВВ трансформацию, используя матрицу, построенную из координат и углов энтити. [todo tested in?] |
GetBoundingMins
|
Vector GetBoundingMins()
|
Берёт вектор, имеющий минимальные границы, центрированный на объекте |
GetBoundingMinsOriented
|
Vector GetBoundingMinsOriented()
|
Берёт вектор, имеющий минимальные границы, центрированный на объекте, с учетом ориентации объекта
Баг:Функция не трансформирует границы правильно и, в некоторых случаях, границы не покроют всё энтити. В качесвте обхода, используйте неориентированные границы и примените ААВВ трансформацию, используя матрицу, построенную из координат и углов энтити. [todo tested in?] |
GetCenter
|
Vector GetCenter()
|
Берёт вектор центра объекта |
GetClassname
|
string GetClassname()
|
|
GetCollisionGroup
|
GetCollisionGroup()
|
Берёт текущюю группу коллизий энтити. |
GetEFlags
|
int GetEFlags()
|
|
GetFlags
|
int GetFlags()
|
|
GetEntityHandle
|
ehandle GetEntityHandle()
|
Берёт энтити в качестве EHANDLE |
GetEntityIndex
|
int GetEntityIndex()
|
|
GetForwardVector
|
Vector GetForwardVector()
|
Берёт вектор энтити, направленный вперёд |
GetFriction
|
float GetFriction()
|
Берёт силу трения PLAYER'а, игнорируемую для объектов |
GetGravity
|
float GetGravity()
|
|
GetHealth
|
int GetHealth()
|
|
GetLeftVector (→ GetRightVector)
|
Vector GetLeftVector()
|
Берёт вектор энтити, направленный направо. Это только для совместимости. |
GetLocalAngles
|
QAngle GetLocalAngles()
|
|
GetLocalOrigin
|
Vector GetLocalOrigin()
|
|
GetLocalVelocity
|
Vector GetLocalVelocity()
|
Берёт относительный вектор энтити |
GetMaxHealth
|
int GetMaxHealth()
|
|
GetModelKeyValues
|
handle GetModelKeyValues()
|
Берёт экземпляр класса KeyValue модели энтити |
GetModelName
|
string GetModelName()
|
Возвращает имя модели |
GetMoveParent
|
handle GetMoveParent()
|
Возвращает родителя энтити, если такой имеется |
GetMoveType
|
int GetMoveType()
|
|
GetName
|
string GetName()
|
|
GetOrigin
|
Vector GetOrigin()
|
Это GetAbsOrigin , только со странным названием функции.
|
GetOwner
|
handle GetOwner()
|
Берёт владельца энтити |
GetPhysAngularVelocity
|
Vector GetPhysAngularVelocity()
|
|
GetPhysVelocity
|
Vector GetPhysVelocity()
|
|
GetPreTemplateName
|
string GetPreTemplateName()
|
Берёт имя энтити с вырезанными уникальными украшениями |
GetRightVector
|
Vector GetRightVector()
|
Берёт вектор энтити, направленный направо |
GetRootMoveParent
|
handle GetRootMoveParent()
|
If in hierarchy, walks up the hierarchy to find the root parent |
GetScriptId
|
string GetScriptId()
|
Retrieve the unique identifier used to refer to the entity within the scripting system. |
GetScriptScope
|
handle GetScriptScope()
|
Retrieve the script-side data associated with an entity |
GetScriptThinkFunc
|
string GetScriptThinkFunc()
|
Retrieve the name of the current script think func |
GetSolid
|
int GetSolid()
|
|
GetSoundDuration
|
float GetSoundDuration(string soundname, string actormodelname)
|
Returns float duration of the sound. Actor model name is optional and can be left null.
Нужно сделать: Actor model name is likely a leftover from Half-Life 2
Предупреждение:Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.
|
GetTeam
|
int GetTeam()
|
|
GetUpVector
|
Vector GetUpVector()
|
Get the up vector of the entity |
GetVelocity (→ GetAbsVelocity)
|
Vector GetVelocity()
|
|
GetWaterLevel
|
int GetWaterLevel()
|
This function tells you how much of the entity is underwater. It returns a value of 0 if not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position).
Примечание:Some entities might not return 1 despite touching water. In some cases you might get 0 and 3 only, or sometimes 0, 2 and 3.
|
GetWaterType
|
int GetWaterType()
|
It returns the type of water the entity is currently submerged in. 32 for water and 16 for slime. |
IsEFlagSet
|
bool IsEFlagSet(int eflag)
|
|
IsPlayer
|
bool IsPlayer()
|
Checks whether the entity is a player or not. |
IsSolid
|
bool IsSolid()
|
|
IsSolidFlagSet
|
bool IsSolidFlagSet(int solidflag)
|
|
IsValid
|
bool IsValid()
|
Checks whether the entity still exists. Useful when storing entity handles and needing to check if the entity was not deleted.
Примечание:This function is never necessary to call on handles returned from built-in script functions, as they are guaranteed to be valid or
null . |
KeyValueFromFloat
|
bool KeyValueFromFloat(string key, float value)
|
Executes KeyValue with a float
Предупреждение:Does not update the internal network state of the entity, which can result in any desired visual changes being delayed for clients if used after spawning. Netprops can be used instead which correctly updates the networking state and results in an immediate update.
|
KeyValueFromInt
|
bool KeyValueFromInt(string key, int value)
|
Executes KeyValue with an int
Предупреждение:See above.
|
KeyValueFromString
|
bool KeyValueFromString(string key, string value)
|
Executes KeyValue with a string
Предупреждение:See above.
|
KeyValueFromVector
|
bool KeyValueFromVector(string key, Vector value)
|
Executes KeyValue with a vector
Предупреждение:See above.
|
Kill
|
void Kill()
|
Removes the entity. Equivalent of firing the Kill I/O input, but instantaneous.
|
LocalEyeAngles
|
handle LocalEyeAngles()
|
Returns the entity's local eye angles |
NextMovePeer
|
handle NextMovePeer()
|
Returns the next entity parented with the entity. Intended for iteration use with FirstMoveChild() .
|
PrecacheModel
|
void PrecacheModel(string modelname)
|
Precache a model
Примечание:This has no return, unlike the global
PrecacheModel function. Use the latter if you need the model index. |
PrecacheScriptSound
|
void PrecacheScriptSound(string soundscript)
|
Precache a sound script. Same as PrecacheSoundScript .
|
PrecacheSoundScript
|
void PrecacheSoundScript(string soundscript)
|
Precache a sound script. Same as PrecacheScriptSound .
|
RemoveEFlags
|
void RemoveEFlags(int eflags)
|
|
RemoveFlag
|
void RemoveFlag(int flags)
|
|
RemoveSolidFlags
|
void RemoveSolidFlags(int solidflags)
|
|
SetAbsAngles
|
void SetAbsAngles(QAngle angles)
|
Set entity pitch, yaw, roll as QAngles
Примечание:Does not work on players, use
SnapEyeAngles instead. |
SetAbsVelocity
|
void SetAbsVelocity(Vector velocity)
|
Sets the current absolute velocity of the entity.
Примечание:Does nothing on VPhysics objects (such as
prop_physics ). For those, use SetPhysVelocity instead. |
SetAbsOrigin
|
void SetAbsOrigin(Vector origin)
|
Sets the absolute origin of the entity. |
SetAngles (→ SetAbsAngles)
|
void SetAngles(float pitch, float yaw, float roll)
|
Set entity angles. |
SetAngularVelocity
|
void SetAngularVelocity(float pitch, float yaw, float roll)
|
Set the local angular velocity. |
SetCollisionGroup
|
void SetCollisionGroup(int collision_group)
|
Set the current collision group of the entity. |
SetDrawEnabled
|
void SetDrawEnabled(bool toggle)
|
Enables drawing if you pass true, disables drawing if you pass false. |
SetEFlags
|
void SetEFlags(int eflags)
|
|
SetForwardVector
|
void SetForwardVector(Vector forward)
|
Set the orientation of the entity to have this forward vector |
SetFriction
|
void SetFriction(float friction)
|
|
SetGravity
|
void SetGravity(float gravity)
|
|
SetHealth
|
void SetHealth(int health)
|
|
SetLocalAngles
|
void SetLocalAngles(QAngle angles)
|
|
SetLocalOrigin
|
void SetLocalOrigin(Vector origin)
|
|
SetMaxHealth
|
void SetMaxHealth(int health)
|
Sets the maximum health this entity can have. Does not update the current health, so SetHealth should be used afterwards.
Примечание:Does nothing on players. Add the
max health additive bonus attribute via AddCustomAttribute instead. |
SetModel
|
void SetModel(string model_name)
|
Set a model for this entity.
Предупреждение:Make sure the model was already precached before using this function or otherwise the game will crash! Alternatively,
SetModelSimple will precache the entity for you. |
SetMoveType
|
void SetMoveType(EMoveType movetype, EMoveCollide movecollide)
|
|
SetOrigin (→ SetAbsOrigin)
|
void SetOrigin(Vectororigin)
|
|
SetOwner
|
void SetOwner(handle entity)
|
Sets this entity's owner |
SetPhysAngularVelocity
|
void SetPhysAngularVelocity(Vector angular_velocity)
|
|
SetPhysVelocity
|
void SetPhysVelocity(Vector velocity)
|
|
SetSize
|
void SetSize(Vector mins, Vector maxs)
|
Sets the bounding box's scale for this entity.
Предупреждение:If any component of mins/maxs is backwards (i.e. mins.x > maxs.x), the engine will exit with a fatal error.
|
SetSolid
|
void SetSolid(int solid)
|
|
SetSolidFlags
|
void SetSolidFlags(int solid_flags)
|
|
SetTeam
|
void SetTeam(int team)
|
Sets entity team.
Примечание:Use
ForceChangeTeam on players instead. |
SetVelocity
|
void SetVelocity(Vector velocity)
|
|
SetWaterLevel
|
void SetWaterLevel(int water_level)
|
This sets how much of the entity is underwater. Setting it to 0 means it is not underwater, 1 if the feet are (touching water brush), 2 if the waist is (center of the hull of the entity), and 3 if the head is (eyes position). |
SetWaterType
|
void SetWaterType(int water_type)
|
Set the type of water the entity is currently submerged in. Generic values to use are 32 for water and 16 for slime. |
StopSound
|
void StopSound(string sound_name)
|
Stops a sound on this entity. |
TakeDamage
|
void TakeDamage(float flDamage, int nDamageType, handle hAttacker)
|
Deals damage to the entity. |
TakeDamageEx
|
void TakeDamageEx(handle hInflictor, handle hAttacker, handle hWeapon, Vector vecDamageForce, Vector vecDamagePosition, float flDamage, int nDamageType)
|
Extended version of TakeDamage .
Примечание:If vecDamageForce is Vector(0, 0, 0), the game will automatically calculate it from vecDamagePosition and flDamage. However, specifying a custom damage force requires a really, really big value to have visible effect (in the hundreds of thousands).
|
TakeDamageCustom
|
void TakeDamageCustom(handle hInflictor, handle hAttacker, handle hWeapon, Vector vecDamageForce, Vector vecDamagePosition, float flDamage, int nDamageType, Constants.ETFDmgCustom nCustomDamageType)
|
Extended version of TakeDamageEx that can apply a custom damage type.
|
Teleport
|
void Teleport(bool use_origin, Vector origin, bool use_angles, QAngle angles, bool use_velocity, Vector velocity)
|
Teleports this entity. For this function, set the bools to false if you want that entity's property unchanged. (do not use null arguments!) |
TerminateScriptScope
|
void TerminateScriptScope()
|
Clear the current script scope for this entity |
ToggleFlag
|
void ToggleFlag(int flags)
|
|
ValidateScriptScope
|
bool ValidateScriptScope()
|
Ensure that an entity's script scope has been created.
Совет:On players, this only needs to be called once. Script scopes remain permanent on players until their entity is removed, i.e. disconnected. The best place to call this is in the
player_spawn event when params.team equals 0 (unassigned). The event is always fired once for team unassigned when the player entity spawns. Similarly, for engineer buildings, this function can also be called once. The player_builtobject is fired when an engineer building is created (or re-placed after moving, but this shouldn't matter). |
Хуки
Хуки - функции, которые вызываются кодом игры в нектороые моменты. Например, когда энтити получает урон, хук OnTakeDamage будет выполнен.
Функции | Написание | Описание | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Input<name>
|
bool Input<name>()
|
Called when the entity receives an input from the I/O system that matches the function's name. The name of the function needs to beInput followed by the name of the input. E.g. for the FireUser1 input, it would beInputFireUser1 .
Примечание:There is an inconsistency with the naming scheme of the inputs. Certain inputs are required in PascalCase format, others in lowercase format. For example,
ForceDrop input on item teamflag must be specified in lowercase, i.e. Inputforcedrop , but another input such as Kill input must be in PascalCase, i.e. InputKill . However it appears this inconsistency varies between different entity classes as well. It is currently unknown what causes this inconsistency.Совет:It may be best to define both variants of these function and have one be a wrapper for the other if the entity class is unknown.
When the function is called, Script Handles of the activator and caller entities are accessible to the function under the variables | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
OnGameEvent_<name>
|
void OnGameEvent_<name>(table params)
|
Called each time a game event with the specified name occurs. The name of the function needs to be OnGameEvent_ followed by the name of the game event. E.g. for the player_spawn input, it would be OnGameEvent_player_spawn .
When the function is called, a table is passed to the function with keys that vary depending on the event. For example, the player_spawn event passes a table with the keys See this page for a list of game events as well as the table passed on each event. Scripts containing OnGameEvent should also issue a call to the function __CollectGameEventCallbacks in order to work properly | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Precache
|
void Precache()
|
Entity function that is called after the script executes, but before the entity is initialized. Can be used to call precache functions for models and sounds on map load.
Совет:This can also be used to modify keyvalues on the entity, and it will use the new values when initializing.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ConnectOutputs
|
void ConnectOutputs(handle scope)
|
Global function called after an entity with an script assigned spawns (i.e. vscripts keyvalue is not blank). Unlike OnPostSpawn , this is called immediately and therefore on map respawn, some entities may not exist during this point.
Примечание:This is a global hook and therefore will only work in global scope, unlike
Precache and OnPostSpawn . | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
OnPostSpawn
|
void OnPostSpawn()
|
Entity function called after the entity is spawned and initialized, at the end of the frame. When map entities are respawned, this effectively runs after all scripts, players etc have been loaded. This could be used to have an entity register itself with a master script, or adjusting the entity parameters in a programmatic way. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
OnTakeDamage
|
void OnTakeDamage(handle params)
|
Called each time an entity takes damage. The script can modify the table entries not prefixed with const, and these will be sent back to the game code.
Примечание:This is a special "entity hook" and works differently than the other hooks, see the example below for how to set it up.
Примечание:The world entity (brushes, static props etc) will not trigger this function by default as it normally can't 'receive' damage. However, the world can be made to 'allow' damage using the following code:
NetProps.SetPropInt(Entities.FindByClassname(null, "worldspawn"), "m_takedamage", 1) . This does not appear to have any adverse side effects, and allows detecting when the world has been hit.Примечание:If called where the damage source is a player's hitscan weapon, player positions or angles fetched within the lag compensation "cone" of the attacker will be using lag compensated positions rather than their real positions.
Примечание:Drowning damage does not trigger this hook. As a workaround, it can be detected in
player_hurt event or disabled by setting m_PainFinished netprop to a very high value.Предупреждение:This is called before any actual damage processing is done. Certain entries might not be calculated or have different values compared to what will be calculated.
Совет:Listen for the
player_hurt or npc_hurt event to effectively have an OnTakeDamage callback after final damage calculations are done.Совет:The hitbox that got hit can be retrieved using the
m_LastHitGroup netprop. On players, the number corresponds to Constants.EHitGroupThe table contains the following keys:
Example: function OnScriptHook_OnTakeDamage(params)
{
printl("OnScriptHook_OnTakeDamage");
if (params.const_entity.IsPlayer())
{
printl(params);
params.damage = 0;
}
}
__CollectGameEventCallbacks(this)
|
CBaseAnimating
Продолжает CBaseEntity
Скрипт дескриптора класса для анимируемых энтити, например, пропов.
Методы
Функция | Написание | Описание |
---|---|---|
DispatchAnimEvents
|
void DispatchAnimEvents(handle entity)
|
Dispatch animation events to a CBaseAnimating entity. |
FindBodygroupByName
|
int FindBodygroupByName(string name)
|
Find a bodygroup ID by name. Returns -1 if the bodygroup does not exist. |
GetAttachmentAngles
|
QAngle GetAttachmentAngles(int ID)
|
Get an attachment's angles as a QAngle, by ID. |
GetAttachmentBone
|
int GetAttachmentBone(int ID)
|
Get an attachment's parent bone index by ID. |
GetAttachmentOrigin
|
Vector GetAttachmentOrigin(int ID)
|
Get an attachment's origin as a Vector, by ID. |
GetBodygroup
|
int GetBodygroup(int ID)
|
Get the bodygroup value by bodygroup ID. |
GetBodygroupName
|
string GetBodygroupName(int ID)
|
Get the bodygroup's name by ID. |
GetBodygroupPartName
|
string GetBodygroupPartName(int group, int part)
|
Get the bodygroup's name by group and part. |
GetBoneAngles
|
QAngle GetBoneAngles(int ID)
|
Get the bone's angles as a QAngle, by ID. |
GetBoneOrigin
|
Vector GetBoneOrigin(int ID)
|
Get the bone's origin Vector by ID. |
GetCycle
|
float GetCycle()
|
Gets the model's current animation cycle rate. |
GetModelScale
|
float GetModelScale()
|
Get the model's scale. |
GetPlaybackRate
|
float GetPlaybackRate()
|
Get the current animation's playback rate. |
GetSequence
|
int GetSequence()
|
Get the current-playing sequence's ID. |
GetSequenceActivityName
|
string GetSequenceActivityName(int ID)
|
Get the activity name for a sequence by sequence ID. |
GetSequenceDuration
|
float GetSequenceDuration(int ID)
|
Get a sequence duration in seconds by sequence ID. |
GetSequenceName
|
string GetSequenceName(int ID)
|
Get a sequence name by sequence ID. |
GetSkin
|
int GetSkin()
|
Gets the current skin index. |
IsSequenceFinished
|
bool IsSequenceFinished()
|
Ask whether the main sequence is done playing. |
LookupActivity
|
int LookupActivity(string activity)
|
Get the named activity index. Returns -1 if the activity does not exist. |
LookupAttachment
|
int LookupAttachment(string name)
|
Get the named attachment index. Returns 0 if the attachment does not exist. |
LookupBone
|
int LookupBone(string bone)
|
Get the named bone index. Returns -1 if the bone does not exist. |
LookupPoseParameter
|
int LookupPoseParameter(string name)
|
Gets the pose parameter's index. Returns -1 if the pose parameter does not exist. |
LookupSequence
|
int LookupSequence(string name)
|
Looks up a sequence by names of sequences or activities. Returns -1 if the sequence does not exist. |
ResetSequence
|
void ResetSequence(int ID)
|
Reset a sequence by sequence ID. If the ID is different than the current sequence, switch to the new sequence. |
SetBodygroup
|
void SetBodygroup(int ID, int value)
|
Set the bodygroup by ID. |
SetCycle
|
void SetCycle(float cycle)
|
Sets the model's current animation cycle from 0 to 1.
Примечание:Does not work correctly on prop dynamic . It will set the value (it interacts with DefaultAnim loop checking; set it to 1.0 and it restarts, and if set on a think function to anything less than 1.0 and it will stop looping) but the animation cycle visually won't be affected by it. You can set it to any value and the animation will not be on the desired cycle.
|
SetModelSimple
|
void SetModelSimple(string model_name)
|
Set a model for this entity. Matches easier behaviour of the SetModel input, automatically precaches, maintains sequence/cycle if possible. |
SetModelScale
|
void SetModelScale(float scale, float change_duration)
|
Changes a model's scale over time. Set the change duration to 0.0 to change the scale instantly. |
SetPlaybackRate
|
void SetPlaybackRate(float rate)
|
Set the current animation's playback rate. |
SetPoseParameter
|
float SetPoseParameter(int ID, float value)
|
Sets a pose parameter value. Returns the effective value after clamping or looping. |
SetSequence
|
void SetSequence(int ID)
|
Plays a sequence by sequence ID.
Предупреждение:This can cause animation stutters when transitioning between sequences. Using
ResetSequence instead will prevent this. Only tested on base boss .Баг:Does not set obj sentrygun sequences correctly, use ResetSequence instead. [todo tested in?] |
SetSkin
|
void SetSkin(int index)
|
Sets the model's skin. |
StopAnimation
|
void StopAnimation()
|
Stop the current animation (same as SetPlaybackRate 0.0) |
StudioFrameAdvance
|
void StudioFrameAdvance()
|
Advance animation frame to some time in the future with an automatically calculated interval |
StudioFrameAdvanceManual
|
void StudioFrameAdvanceManual(float dt)
|
Advance animation frame to some time in the future with a manual interval |
CBaseCombatWeapon
Extends CBaseAnimating
Script handle class for any weapon entities that can be part of a player's inventory.
Team Fortress 2's weapons leave Clip2
unused, so those functions can be ignored
Methods
Function | Signature | Description | |
---|---|---|---|
CanBeSelected
|
bool CanBeSelected()
|
Can this weapon be selected | |
Clip1
|
int Clip1()
|
Current ammo in clip1 | |
Clip2
|
int Clip2()
|
Current ammo in clip2 | |
GetDefaultClip1
|
int GetDefaultClip1()
|
Default size of clip1 | |
GetDefaultClip2
|
int GetDefaultClip2()
|
Default size of clip2 | |
GetMaxClip1
|
int GetMaxClip1()
|
Max size of clip1 | |
GetMaxClip2
|
int GetMaxClip2()
|
Max size of clip2 | |
GetName
|
string GetName()
|
Gets the weapon's name | |
GetPosition
|
int GetPosition()
|
Gets the weapon's current position | |
GetPrimaryAmmoCount
|
int GetPrimaryAmmoCount()
|
Current primary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF) | |
GetPrimaryAmmoType
|
int GetPrimaryAmmoType()
|
Returns the primary ammo type | |
GetPrintName
|
string GetPrintName()
|
Gets the weapon's print name | |
GetSecondaryAmmoCount
|
int GetSecondaryAmmoCount()
|
Current secondary ammo count if no clip is used or to give a player if they pick up this weapon legacy style (not TF) | |
GetSecondaryAmmoType
|
int GetSecondaryAmmoType()
|
Returns the secondary ammo type | |
GetSlot
|
int GetSlot()
|
Gets the weapon's current slot | |
GetSubType
|
int GetSubType()
|
Get the weapon subtype | |
GetWeaponFlags
|
int GetWeaponFlags()
|
Get the weapon flags | |
GetWeight
|
int GetWeight()
|
Get the weapon weighting/importance | |
HasAnyAmmo
|
bool HasAnyAmmo()
|
Do we have any ammo? | |
HasPrimaryAmmo
|
bool HasPrimaryAmmo()
|
Do we have any primary ammo? | |
HasSecondaryAmmo
|
bool HasSecondaryAmmo()
|
Do we have any secondary ammo? | |
IsAllowedToSwitch
|
bool IsAllowedToSwitch()
|
Are we allowed to switch to this weapon? | |
IsMeleeWeapon
|
bool IsMeleeWeapon()
|
Returns whether this is a melee weapon | |
PrimaryAttack
|
void PrimaryAttack()
|
Force a primary attack
Совет:This allows arbitrarily firing weapons that do not actually belong to any player. This can be useful for creating entities that might not fully work on their own, for example rockets. Most weapons will work as long as the
m_hOwner netprop on the weapon is set to an existing player. Weapons spawned manually might also need SetClip(-1) , and m_flNextPrimaryAttack (or m_flSecondaryPrimaryAttack ) set to 0 before calling this function to always allow firing without delays.Предупреждение:Hitscan and melee weapons require lag compensation information to be present, or the game will crash! Calling this from a player's think function or OnTakeDamage hook (whose source is a player's hitscan weapon) is sufficient. Alternatively, lag compensation can be temporarily disabled which allows calling this function from anywhere, with the side effect of poor hit registration for high latency players. This can be achieved by setting the
m_bLagCompensation netprop on the player to to false, calling this function, and reverting it back to true.Предупреждение:This will play the weapon's fire sound to everyone except the owner. If the sound is desired, the sound can be played to the owner exclusively via
EmitSoundEx . If the sound is not desired, it can be stopped by calling StopSound after this function. | |
SecondaryAttack
|
void SecondaryAttack()
|
Force a secondary attack
Предупреждение:See above.
| |
SetClip1
|
void SetClip1(int amount)
|
Set current ammo in clip1. | |
SetClip2
|
void SetClip2(int amount)
|
Set current ammo in clip2. | |
SetCustomViewModel
|
void SetCustomViewModel(string model_name)
|
Sets a custom view model for this weapon by model name. | |
SetCustomViewModelModelIndex
|
void SetCustomViewModelModelIndex(int model_index)
|
Sets a custom view model for this weapon by modelindex. | |
SetSubType
|
void SetSubType(int subtype)
|
Set the weapon subtype | |
UsesClipsForAmmo1
|
bool UsesClipsForAmmo1()
|
Do we use clips for ammo 1? | |
UsesClipsForAmmo2
|
bool UsesClipsForAmmo2()
|
Do we use clips for ammo 2? | |
UsesPrimaryAmmo
|
bool UsesPrimaryAmmo()
|
Do we use primary ammo? | |
UsesSecondaryAmmo
|
bool UsesSecondaryAmmo()
|
Do we use secondary ammo? | |
VisibleInWeaponSelection
|
bool VisibleInWeaponSelection()
|
Is this weapon visible in weapon selection |
CBaseFlex
Extends CBaseAnimating
Animated characters who have vertex flex capability (e.g., facial expressions).
Methods
Function | Signature | Description |
---|---|---|
PlayScene
|
float PlayScene(string scene_file, float delay)
|
Play the specified .vcd file, causing the related characters to speak and subtitles to play.
Совет:Open
tf2_misc_dir.vpk and browse the files in scripts/talker/... to find .vcd files. Alternatively, use the rr_debugresponses 1 command with developer 1 to find .vcds from in-game voicelines. |
CBaseCombatCharacter
Extends CBaseFlex
Combat entities with similar movement capabilities to a player.
Methods
Function | Signature | Description |
---|---|---|
GetLastKnownArea
|
handle GetLastKnownArea()
|
Return the last nav area occupied, NULL if unknown.
See CTFNavArea. |
CBasePlayer
Extends CBaseCombatCharacter
Script handle class for player entities.
Methods
Function | Signature | Description |
---|---|---|
GetForceLocalDraw
|
bool GetForceLocalDraw()
|
Whether the player is being forced by SetForceLocalDraw to be drawn. |
GetPlayerMaxs
|
Vector GetPlayerMaxs()
|
Get a vector containing max bounds of the player in local space. The player's model scale will affect the result. |
GetPlayerMins
|
Vector GetPlayerMins()
|
Get a vector containing min bounds of the player in local space. The player's model scale will affect the result. |
GetScriptOverlayMaterial
|
string GetScriptOverlayMaterial()
|
Gets the current overlay material set by SetScriptOverlayMaterial. |
IsNoclipping
|
bool IsNoclipping()
|
Returns true if the player is in noclip mode. |
SetForceLocalDraw
|
void SetForceLocalDraw(bool forceDraw)
|
Forces the player to be drawn as if they were in thirdperson. |
SetScriptOverlayMaterial
|
void SetScriptOverlayMaterial(string material)
|
Sets the overlay material that can't be overriden by other overlays. E.g. Jarate. |
SnapEyeAngles
|
void SnapEyeAngles(QAngle angles)
|
Snap the player's eye angles to this. |
ViewPunch
|
void ViewPunch(QAngle angleOffset)
|
Ow! Punches the player's view. |
ViewPunchReset
|
void ViewPunchReset(float tolerance)
|
Reset's the player's view punch if the offset stays below the given tolerance. |
CBaseMultiplayerPlayer
Extends CBasePlayer
Script handle sub-class for player entities in multiplayer games. No additional methods.
CEconEntity
Extends CBaseAnimating
Script handle class for economic exquisite equippables, meaning hats and weapons.
Methods
Function | Signature | Description |
---|---|---|
AddAttribute
|
void AddAttribute(string name, float value, float duration)
|
Add an attribute to the entity. Set duration to -1 for the attribute to be applied forever. |
RemoveAttribute
|
void RemoveAttribute(string name)
|
Remove an attribute from the entity. |
ReapplyProvision
|
void ReapplyProvision()
|
Relinks attributes to provisioners, e.g. calling this on a weapon will add it's attributes to the player. |
CTFPlayer
Extends CBaseMultiplayerPlayer
Script handle class for player entities of Team Fortress 2.
Methods
Function | Signature | Description |
---|---|---|
AddCond
|
void AddCond(ETFCond cond)
|
|
AddCondEx
|
void AddCondEx(ETFCond cond, float duration, handle provider)
|
|
AddCurrency
|
void AddCurrency(int amount)
|
Kaching! Give the player some cash for game modes with upgrades, ie. MvM |
AddCustomAttribute
|
void AddCustomAttribute(string name, float value, float duration)
|
Add a custom attribute to the player. Set duration to -1 for the attribute to be applied forever.
Примечание:This does not work when applied in the
player_spawn event, because custom attributes are cleared immediately after the event. As a workaround, it can be applied with a delay. See the example code. |
AddHudHideFlags
|
void AddHudHideFlags(int flags)
|
Hides a hud element based on Constants.FHideHUD |
ApplyPunchImpulseX
|
bool ApplyPunchImpulseX(float impulse)
|
Apply a view punch along the pitch angle. Used to flinch players when hit. If the player is a fully charged scoped-in sniper and the weapon has the aiming_no_flinch attribute, the punch will not apply. Returns true if the punch was applied.
|
BleedPlayer
|
void BleedPlayer(float duration)
|
Make a player bleed for a set duration of time. |
BleedPlayerEx
|
void BleedPlayerEx(float duration, int damage, bool endless, int nCustomDamageType)
|
Make a player bleed for a set duration of time, or forever, with specific damage per tick and damage_custom index. |
CancelTaunt
|
void CancelTaunt()
|
Cancels any taunt in progress |
CanAirDash
|
bool CanAirDash()
|
Can the player air dash/double jump? |
CanBeDebuffed
|
bool CanBeDebuffed()
|
|
CanBreatheUnderwater
|
bool CanBreatheUnderwater()
|
|
CanDuck
|
bool CanDuck()
|
Can the player duck? |
CanGetWet
|
bool CanGetWet()
|
Can the player get wet by jarate/milk? |
CanJump
|
bool CanJump()
|
Can the player jump? |
ClearCustomModelRotation
|
void ClearCustomModelRotation()
|
|
ClearSpells
|
void ClearSpells()
|
|
ClearTauntAttack
|
void ClearTauntAttack()
|
Stops active taunt from damaging or cancels Rock-Paper-Scissors result |
CanPlayerMove
|
bool CanPlayerMove()
|
Can the player move? |
DoTauntAttack
|
void DoTauntAttack()
|
Performs taunts attacks if available. Player must be already taunting and taunt must have a valid attack assigned (taunt attack name attribute)
|
DropFlag
|
void DropFlag(bool silent)
|
Force player to drop the flag. |
DropRune
|
void DropRune(bool apply_force, int team)
|
Force player to drop the rune.
Совет:This can be abused to spawn arbitrary Mannpower powerups. See the example .
|
EndLongTaunt
|
void EndLongTaunt()
|
Stops a looping taunt (obeys minimum time rules and plays outro animation if available) |
EquipWearableViewModel
|
void EquipWearableViewModel(handle ent)
|
Equips a wearble on the viewmodel. Intended to be used with tf_wearable_vm entities. |
ExtinguishPlayerBurning
|
void ExtinguishPlayerBurning()
|
|
FiringTalk
|
void FiringTalk()
|
Makes eg. a heavy go AAAAAAAAAAaAaa like they are firing their minigun.
Примечание:This only works in a few situations as it requires certain gameplay conditions to be true. An example of when this will work: when the player is invulnerable.
Баг:Unfortunately does not work for Heavy's minigun due to the above quirk. [todo tested in?] |
ForceChangeTeam
|
void ForceChangeTeam(int team, bool full_team_switch)
|
Force player to change their team. Setting the bool to true will not remove nemesis relationships or reset the player's class, as well as not slaying the player.
Примечание:This will not work if a player is in a duel. Setting the
m_bIsCoaching netprop to true on the player and reverting it afterwards is a workaround. |
ForceRegenerateAndRespawn
|
void ForceRegenerateAndRespawn()
|
Force regenerates and respawns the player |
ForceRespawn
|
void ForceRespawn()
|
Force respawns the player |
GetActiveWeapon
|
handle GetActiveWeapon()
|
Get the player's current weapon |
GetBackstabs
|
int GetBackstabs()
|
|
GetBonusPoints
|
int GetBonusPoints()
|
|
GetBotType
|
int GetBotType()
|
|
GetBuildingsDestroyed
|
int GetBuildingsDestroyed()
|
|
GetCaptures
|
int GetCaptures()
|
|
GetClassEyeHeight
|
Vector GetClassEyeHeight()
|
Gets the eye height of the player |
GetCondDuration
|
float GetCondDuration(ETFCond cond)
|
Returns duration of the condition. Returns 0 if the cond is not applied. Returns -1 if the cond is infinite. |
GetCurrency
|
int GetCurrency()
|
Get player's cash for game modes with upgrades, ie. MvM |
GetCurrentTauntMoveSpeed
|
float GetCurrentTauntMoveSpeed()
|
|
GetDefenses
|
int GetDefenses()
|
|
GetDisguiseAmmoCount
|
int GetDisguiseAmmoCount()
|
|
GetDisguiseTarget
|
handle GetDisguiseTarget()
|
|
GetDisguiseTeam
|
int GetDisguiseTeam()
|
|
GetDominations
|
int GetDominations()
|
|
GetGrapplingHookTarget
|
handle GetGrapplingHookTarget()
|
What entity is the player grappling? |
GetHeadshots
|
int GetHeadshots()
|
|
GetHealPoints
|
int GetHealPoints()
|
|
GetHealTarget
|
handle GetHealTarget()
|
Who is the medic healing? |
GetHudHideFlags
|
int GetHudHideFlags()
|
Gets current hidden hud elements |
GetInvulns
|
int GetInvulns()
|
|
GetKillAssists
|
int GetKillAssists()
|
|
GetLastWeapon
|
handle GetLastWeapon()
|
|
GetNextChangeClassTime
|
float GetNextChangeClassTime()
|
Get next change class time. |
GetNextChangeTeamTime
|
float GetNextChangeTeamTime()
|
Get next change team time. |
GetNextRegenTime
|
float GetNextRegenTime()
|
Get next health regen time. |
GetPlayerClass
|
int GetPlayerClass()
|
|
GetRageMeter
|
float GetRageMeter()
|
|
GetResupplyPoints
|
int GetResupplyPoints()
|
|
GetRevenge
|
int GetRevenge()
|
|
GetScoutHypeMeter
|
float GetScoutHypeMeter()
|
|
GetSpyCloakMeter
|
float GetSpyCloakMeter()
|
|
GetTeleports
|
int GetTeleports()
|
|
GetTauntAttackTime
|
float GetTauntAttackTime()
|
Timestamp until a taunt attack "lasts". 0 if unavailable |
GetTauntRemoveTime
|
float GetTauntRemoveTime()
|
Timestamp until taunt is stopped |
GetVehicleReverseTime
|
float GetVehicleReverseTime()
|
Timestamp when kart was reversed |
GetTimeSinceCalledForMedic
|
float GetTimeSinceCalledForMedic()
|
When did the player last call medic |
GrantOrRemoveAllUpgrades
|
void GrantOrRemoveAllUpgrades(bool remove, bool refund)
|
|
HasItem
|
bool HasItem()
|
Currently holding an item? Eg. capture flag
Совет:Fetch the
m_hItem netprop to get the entity handle. |
HandleTauntCommand
|
void HandleTauntCommand(int taunt_slot)
|
Spoofs a taunt command from the player, as if they selected this taunt. |
IgnitePlayer
|
void IgnitePlayer()
|
|
InAirDueToExplosion
|
bool InAirDueToExplosion()
|
|
InAirDueToKnockback
|
bool InAirDueToKnockback()
|
|
InCond
|
bool InCond(ETFCond cond)
|
|
IsAirDashing
|
bool IsAirDashing()
|
|
IsAllowedToRemoveTaunt
|
bool IsAllowedToRemoveTaunt()
|
Returns true if the taunt will be stopped |
IsAllowedToTaunt
|
bool IsAllowedToTaunt()
|
|
IsBotOfType
|
bool IsBotOfType(int type)
|
|
IsCallingForMedic
|
bool IsCallingForMedic()
|
Is this player calling for medic? |
IsCarryingRune
|
bool IsCarryingRune()
|
|
IsControlStunned
|
bool IsControlStunned()
|
|
IsCritBoosted
|
bool IsCritBoosted()
|
|
IsFakeClient
|
bool IsFakeClient()
|
|
IsFireproof
|
bool IsFireproof()
|
|
IsFullyInvisible
|
bool IsFullyInvisible()
|
|
IsHypeBuffed
|
bool IsHypeBuffed()
|
|
IsImmuneToPushback
|
bool IsImmuneToPushback()
|
|
IsInspecting
|
bool IsInspecting()
|
|
IsInvulnerable
|
bool IsInvulnerable()
|
|
IsJumping
|
bool IsJumping()
|
|
IsMiniBoss
|
bool IsMiniBoss()
|
Is this player an MvM mini-boss? |
IsParachuteEquipped
|
bool IsParachuteEquipped()
|
|
IsPlacingSapper
|
bool IsPlacingSapper()
|
Returns true if we placed a sapper in the last few moments |
IsRageDraining
|
bool IsRageDraining()
|
|
IsRegenerating
|
bool IsRegenerating()
|
|
IsSapping
|
bool IsSapping()
|
Returns true if we are currently sapping |
IsSnared
|
bool IsSnared()
|
|
IsStealthed
|
bool IsStealthed()
|
|
IsTaunting
|
bool IsTaunting()
|
|
IsUsingActionSlot
|
bool IsUsingActionSlot()
|
|
IsViewingCYOAPDA
|
bool IsViewingCYOAPDA()
|
|
IsViewingCYOAPDA
|
bool IsViewingCYOAPDA()
|
|
Regenerate
|
void Regenerate(bool refill_health_ammo)
|
Resupplies a player. If refill health/ammo is set, clears negative conds, gives back player health/ammo |
RemoveAllItems
|
void RemoveAllItems(bool unused)
|
Баг:This does not actually remove all items. It only drops the passtime ball, intelligence, disables radius healing, and hides the Spy invis watch. [todo tested in?] |
RemoveAllObjects
|
void RemoveAllObjects(bool explode)
|
Remove all player objects. Eg. dispensers/sentries. |
RemoveCond
|
void RemoveCond(ETFCond cond)
|
|
RemoveCondEx
|
void RemoveCondEx(ETFCond cond, bool ignoreDuration)
|
|
RemoveCurrency
|
void RemoveCurrency(int amount)
|
Take away money from a player for reasons such as ie. spending. |
RemoveCustomAttribute
|
void RemoveCustomAttribute(string name)
|
Remove a custom attribute to the player |
RemoveDisguise
|
void RemoveDisguise()
|
Undisguise a spy. |
RemoveHudHideFlags
|
void RemoveHudHideFlags(int flags)
|
Unhides a hud element based on Constants.FHideHUD |
RemoveInvisibility
|
void RemoveInvisibility()
|
Un-invisible a spy. |
RemoveTeleportEffect
|
void RemoveTeleportEffect()
|
|
ResetScores
|
void ResetScores()
|
|
RollRareSpell
|
void RollRareSpell()
|
|
SetCondDuration
|
void SetCondDuration(ETFCond cond, float duration)
|
|
SetCurrency
|
void SetCurrency(int amount)
|
Set player's cash for game modes with upgrades, ie. MvM |
SetCurrentTauntMoveSpeed
|
void SetCurrentTauntMoveSpeed(float speed)
|
|
SetCustomModel
|
void SetCustomModel(string model_name)
|
|
SetCustomModelOffset
|
void SetCustomModelOffset(Vector offset)
|
|
SetCustomModelRotates
|
void SetCustomModelRotates(bool toggle)
|
|
SetCustomModelRotation
|
void SetCustomModelRotation(QAngle angles)
|
|
SetCustomModelVisibleToSelf
|
void SetCustomModelVisibleToSelf(bool toggle)
|
|
SetCustomModelWithClassAnimations
|
void SetCustomModelWithClassAnimations(string model_name)
|
|
SetDisguiseAmmoCount
|
void SetDisguiseAmmoCount(int count)
|
|
SetForcedTauntCam
|
void SetForcedTauntCam(int toggle)
|
|
SetGrapplingHookTarget
|
void SetGrapplingHookTarget(handle entity, bool bleed)
|
Set the player's target grapple entity |
SetHudHideFlags
|
void SetHudHideFlags(int flags)
|
Force hud hide flags to a value based on Constants.FHideHUD |
SetIsMiniBoss
|
void SetIsMiniBoss(bool toggle)
|
Make this player an MvM mini-boss. |
SetNextChangeClassTime
|
void SetNextChangeClassTime(float time)
|
Set next change class time. |
SetNextChangeTeamTime
|
void SetNextChangeTeamTime(float time)
|
Set next change team time. |
SetNextRegenTime
|
void SetNextRegenTime(float time)
|
Set next available resupply time. |
SetPlayerClass
|
void SetPlayerClass(int class)
|
Sets the player class. Updates the player's visuals and model.
Примечание:Does not force the class to be changed and can be buggy for server-side scripts. This can be resolved by calling
NetProps.SetPropInt(player, "m_Shared.m_iDesiredPlayerClass", classIndex) after SetPlayerClass and before ForceRegenerateAndRespawn . This resolves issues like the player respawning as their "desired" class instead or loadout showing the desired class rather than what they are.Примечание:Does not regenerate class properties, such as health or weapons. This can be done by calling
ForceRegenerateAndRespawn afterwards.Предупреждение:If the player is not respawned, the hitbox set will be used from the old class! Calling
SetCustomModel with a blank parameter is sufficient to update it. |
SetRageMeter
|
void SetRageMeter(float percent)
|
Sets rage meter from 0 - 100. |
SetRPSResult
|
void SetRPSResult(int result)
|
Rig the result of Rock-Paper-Scissors (0 - rock, 1 - paper, 2 - scissors) |
SetScoutHypeMeter
|
void SetScoutHypeMeter(float percent)
|
Sets hype meter from 0 - 100. |
SetSpyCloakMeter
|
void SetSpyCloakMeter(float)
|
Sets cloakmeter from 0 - 100. |
SetVehicleReverseTime
|
void SetVehicleReverseTime(float time)
|
Set the timestamp when kart was reversed |
SetUseBossHealthBar
|
void SetUseBossHealthBar(bool toggle)
|
|
StopTaunt
|
void StopTaunt(bool remove_prop)
|
Stops current taunt. If remove_prop is true, the taunt prop will be immediately deleted instead of potentially delaying |
Taunt
|
void Taunt(int taunt_index, int taunt_concept)
|
Performs a taunt if allowed. For taunt index, see Constants.FTaunts. For concepts, see MP_CONCEPT List. Concept is the "voiceline" index to use with the taunt. For TAUNT_SHOW_ITEM and TAUNT_BASE_WEAPON this is set automatically. TAUNT_LONG is not supported.
Совет:TAUNT_MISC_ITEM with a concept of
MP_CONCEPT_TAUNT_LAUGH will make the player laugh. Concept MP_CONCEPT_TAUNT_REPLAY will play the replay taunt. |
TryToPickupBuilding
|
bool TryToPickupBuilding()
|
Make the player attempt to pick up a building in front of them |
UpdateSkin
|
UpdateSkin(int skin)
|
|
WasInCond
|
bool WasInCond(ETFCond cond)
|
|
Weapon_CanUse
|
bool Weapon_CanUse(handle weapon)
|
|
Weapon_Drop
|
void Weapon_Drop(handle weapon)
|
Does nothing! |
Weapon_DropEx
|
void Weapon_DropEx(handle weapon, Vector target, Vector velocity)
|
Does nothing! |
Weapon_Equip
|
void Weapon_Equip(handle weapon)
|
|
Weapon_SetLast
|
void Weapon_SetLast(handle weapon)
|
|
Weapon_ShootPosition
|
Vector Weapon_ShootPosition()
|
|
Weapon_Switch
|
void Weapon_Switch(handle weapon)
|
CTFBot
Extends CTFPlayer and NextBotCombatCharacter
Script handle class for bot-controlled players aka tf bot . Beep boop.
Methods
Function | Signature | Description |
---|---|---|
AddBotAttribute
|
void AddBotAttribute(int attribute)
|
Sets attribute flags on this TFBot |
AddBotTag
|
void AddBotTag(string tag)
|
Adds a bot tag |
AddWeaponRestriction
|
void AddWeaponRestriction(int flags)
|
Adds weapon restriction flags |
ClearAllBotAttributes
|
void ClearAllBotAttributes()
|
Clears all attribute flags on this TFBot |
ClearAllBotTags
|
void ClearAllBotTags()
|
Clears bot tags |
ClearAllWeaponRestrictions
|
void ClearAllWeaponRestrictions()
|
Removes all weapon restriction flags |
ClearAttentionFocus
|
void ClearAttentionFocus()
|
Clear current focus |
DelayedThreatNotice
|
void DelayedThreatNotice(handle threat, float delay)
|
Notice the threat after a delay in seconds |
DisbandCurrentSquad
|
void DisbandCurrentSquad()
|
Forces the current squad to be entirely disbanded by everyone |
FindVantagePoint
|
handle FindVantagePoint(float max_distance)
|
Get the nav area of the closest vantage point (within distance) |
GenerateAndWearItem
|
void GenerateAndWearItem(string item_name)
|
Give me an item! |
GetHomeArea
|
handle GetHomeArea()
|
Sets the home nav area of the bot |
GetDifficulty
|
ETFBotDifficultyType GetDifficulty()
|
Returns the bot's difficulty level |
GetMaxVisionRangeOverride
|
float GetMaxVisionRangeOverride()
|
Gets the max vision range override for the bot Предупреждение:MaxVisionRange overrides, as well as certain other bot modifiers, can persist after a bot has been moved to spectator and assigned a new class/loadout in MvM! Identifying MvM bots by the MaxVisionRange override set in a popfile may not be reliable.
|
GetNearestKnownSappableTarget
|
handle GetNearestKnownSappableTarget()
|
Gets the nearest known sappable target |
GetSpawnArea
|
handle GetSpawnArea()
|
Return the nav area of where we spawned |
GetSquadFormationError
|
float GetSquadFormationError()
|
Gets our formation error coefficient. |
HasBotAttribute
|
bool HasBotAttribute(int attribute)
|
Checks if this TFBot has the given attributes |
HasBotTag
|
bool HasBotTag(string tag)
|
Checks if this TFBot has the given bot tag |
HasWeaponRestriction
|
bool HasWeaponRestriction(int flags)
|
Checks if this TFBot has the given weapon restriction flags |
IsAmmoFull
|
bool IsAmmoFull()
|
|
IsAmmoLow
|
bool IsAmmoLow()
|
|
IsAttentionFocused
|
bool IsAttentionFocused()
|
Is our attention focused right now? |
IsAttentionFocusedOn
|
bool IsAttentionFocusedOn(handle entity)
|
Is our attention focused on this entity |
IsDifficulty
|
bool IsDifficulty(int difficulty)
|
Returns true/false if the bot's difficulty level matches. |
IsInASquad
|
bool IsInASquad()
|
Checks if we are in a squad |
IsWeaponRestricted
|
bool IsWeaponRestricted(handle weapon)
|
Checks if the given weapon is restricted for use on the bot |
LeaveSquad
|
void LeaveSquad()
|
Makes us leave the current squad (if any) |
PressAltFireButton
|
void PressAltFireButton(float duration)
|
|
PressFireButton
|
void PressFireButton(float duration)
|
|
PressSpecialFireButton
|
void PressSpecialFireButton(float duration)
| |
RemoveBotAttribute
|
void RemoveBotAttribute(int attribute)
|
Removes attribute flags on this TFBot |
RemoveBotTag
|
void RemoveBotTag(string tag)
|
Removes a bot tag |
RemoveWeaponRestriction
|
void RemoveWeaponRestriction(int flags)
|
Removes weapon restriction flags |
SetAttentionFocus
|
void SetAttentionFocus(handle entity)
|
Sets our current attention focus to this entity |
SetAutoJump
|
void SetAutoJump(float minTime, float maxTime)
|
Sets if the bot should automatically jump, and how often. |
SetDifficulty
|
void SetDifficulty(int difficulty)
|
Sets the bots difficulty level |
SetHomeArea
|
void SetHomeArea(handle area)
|
Set the home nav area of the bot, may be null. |
SetMaxVisionRangeOverride
|
void SetMaxVisionRangeOverride(float range)
|
Sets max vision range override for the bot |
SetScaleOverride
|
void SetScaleOverride(float scale)
|
Sets the scale override for the bot |
SetShouldQuickBuild
|
void SetShouldQuickBuild(bool toggle)
|
Sets if the bot should build instantly |
SetSquadFormationError
|
void SetSquadFormationError(float coefficient)
|
Sets our formation error coefficient. |
ShouldAutoJump
|
bool ShouldAutoJump()
|
Returns if the bot should automatically jump |
ShouldQuickBuild
|
bool ShouldQuickBuild()
|
Returns if the bot should build instantly |
UpdateDelayedThreatNotices
|
void UpdateDelayedThreatNotices()
|
Convars
Game Instance: Convars
An interface to manipulate the convars on the server.
rcon_password
) cannot be accessed.Methods
Function | Signature | Description |
---|---|---|
GetBool
|
bool GetBool(string name)
|
Returns the convar as a bool. May return null if no such convar. |
GetClientConvarValue
|
string GetClientConvarValue(string name, int entindex)
|
Returns the convar value for the entindex as a string. Only works on client convars with the FCVAR_USERINFO flag.
Совет:The list of available client convars can be printed in console using the
findflags USERINFO command.Примечание:Notable client convars available:
|
GetInt
|
int GetInt(string name)
|
Returns the convar as an int. May return null if no such convar. |
GetStr
|
string GetStr(string name)
|
Returns the convar as a string. May return null if no such convar. |
GetFloat
|
float GetFloat(string name)
|
Returns the convar as a float. May return null if no such convar. |
IsConVarOnAllowList
|
bool IsConVarOnAllowList(string name)
|
Checks if the convar is allowed to be used and is in cfg/vscript_convar_allowlist.txt. Please be nice with this and use it for *compatibility* if you need check support and NOT to force server owners to allow hostname to be set... or else this will simply lie and return true in future. ;-) You have been warned! |
SetValue
|
void SetValue(string name, any value)
|
Sets the value of the convar. The convar must be in cfg/vscript_convar_allowlist.txt to be set. Convars marked as cheat-only can be set even if sv_cheats is off. Convars marked as dev-only (i.e. not visible in console) can also be set. Supported types are bool, int, float, string.
Предупреждение:For changes intended to persist for the whole map, set these at the start of each round instead of only once. Otherwise, custom server configs may load after the initial script and not use the correct settings.
|
CEntities
Game Instance: Entities
An interface to find and iterate over the script handles for the entities in play. To iterate over a set of entities, pass null to the previous parameter in the appropriate method to start an iteration. A reference to a previously-found entity can be used instead to continue a search.
The following are two equivalent examples and iterate over all weapons on the map:
local ent = null;
while ( ent = Entities.FindByClassname(ent, "tf_weapon_*") )
{
// ...
}
|
for (local ent; ent = Entities.FindByName(ent, "tf_weapon_*"); )
{
// ...
}
|
- The variable name
ent
is arbitrary. - Indeed, we mean "=" and not "==" in the loop conditions! The loops end if
ent
becomesnull
, which happens when no matching entities have an entity index higher to the one in previous parameter. - Semicolons are optional, except in the header of the
for
statement. - The string parameters of the
FindBy...
functions support the wildcard star*
. In the above example,FindByClassname
only returns either a handle of an entity whose classname begins with "tf_weapon_
" or it returnsnull
.
Methods
Function | Signature | Description |
---|---|---|
CreateByClassname
|
handle CreateByClassname(string classname)
|
Creates an entity by classname.
Совет:Example usage:
local prop = Entities.CreateByClassname("prop_dynamic");
|
DispatchSpawn
|
void DispatchSpawn(handle entity)
|
Dispatches spawn of an entity! Use this on entities created via CreateByClassname to actually spawn them into the world.
Примечание:Calling this on players will cause them to respawn.
|
FindByClassname
|
handle FindByClassname(handle previous, string classname)
|
Find entities by the string of their classname keyvalue. Pass 'null' value to start an iteration, or reference to a previously found entity to continue a search
Примечание:The classname keyvalue of an entity can be manipulated and does not necessarily reflect its code class. There might be entities that have a different classname than the one they are created with. For example you can spawn a "prop_dynamic" then change its classname to "my_prop", and it will retain the functionality of its code class while also not showing up when searching for "prop_dynamic".
|
FindByClassnameNearest
|
handle FindByClassnameNearest(string classname, Vector center, float radius)
|
Find entities by classname nearest to a point within a radius. |
FindByClassnameWithin
|
handle FindByClassnameWithin(handle previous, string classname, Vector center, float radius)
|
Find entities by classname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search |
FindByModel
|
handle FindByModel(handle previous, string modelname)
|
Find entities by the string of their model keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|
FindByName
|
handle FindByName(handle previous, string targetname)
|
Find entities by the string of their targetname keyvalue. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search |
FindByNameNearest
|
handle FindByNameNearest(string targetname, Vector center, float radius)
|
Find entities by targetname nearest to a point within a radius. |
FindByNameWithin
|
handle FindByNameWithin(handle previous, string targetname, Vector center, float radius)
|
Find entities by targetname within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search |
FindByTarget
|
handle FindByTarget(handle previous, string target)
|
Find entities by the string of their target keyvalue.[подтвердить] Pass 'null' to start an iteration, or reference to a previously found entity to continue a search
|
FindInSphere
|
handle FindInSphere(handle previous, Vector center, float radius)
|
Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search |
First
|
handle First()
|
Begin an iteration over the list of entities |
Next
|
handle Next(handle previous)
|
At the given reference of a previously-found entity, returns the next one after it in the list. |
Script handle class for areas part of the navigation mesh .
Methods
Function | Signature | Description |
---|---|---|
AddIncomingConnection
|
void AddIncomingConnection(handle area, int dir)
|
Add areas that connect TO this area by a ONE-WAY link |
ClearAttributeTF
|
void ClearAttributeTF(int bits)
|
Clear TF-specific area attribute bits. |
ComputeClosestPointInPortal
|
Vector ComputeClosestPointInPortal(handle to, ENavDirType dir, Vector closePos)
|
Compute closest point within the "portal" between to an area's direction from the given position. |
ComputeDirection
|
int ComputeDirection(Vector point)
|
Return direction from this area to the given point. |
ConnectTo
|
void ConnectTo(handle area, int dir)
|
Connect this area to given area in given direction. |
Contains
|
bool Contains(handle area)
|
Return true if other area is on or above this area, but no others. |
ContainsOrigin
|
bool ContainsOrigin(Vector point)
|
Return true if given point is on or above this area, but no others. |
DebugDrawFilled
|
void DebugDrawFilled(int r, int g, int b, int a, float duration, bool noDepthTest, float margin)
|
Draw area as a filled rectangle of the given color. |
Disconnect
|
void Disconnect(handle area)
|
Disconnect this area from given area. |
FindRandomSpot
|
Vector FindRandomSpot()
|
Get random origin within extent of area. |
GetAdjacentArea
|
handle GetAdjacentArea(int dir, int n)
|
Return the n'th adjacent area in the given direction |
GetAdjacentAreas
|
void GetAdjacentAreas(int dir, handle table)
|
Fills a passed in table with all adjacent areas in the given direction. |
GetAdjacentCount
|
int GetAdjacentCount(ENavDirType dir)
|
Get the number of adjacent areas in the given direction. |
GetAttributes
|
int GetAttributes()
|
Get area attribute bits. |
GetAvoidanceObstacleHeight
|
float GetAvoidanceObstacleHeight()
|
Returns the maximum height of the obstruction above the ground. |
GetCenter
|
Vector GetCenter()
|
Get center origin of area. |
GetCorner
|
Vector GetCorner(ENavDirType dir)
|
Get corner origin of area. |
GetDistanceSquaredToPoint
|
float GetDistanceSquaredToPoint(Vector pos)
|
Return shortest distance between point and this area. |
GetDoor
|
handle GetDoor()
|
Returns the door entity above the area. |
GetElevator
|
handle GetElevator()
|
Returns the elevator if in an elevator's path. |
GetElevatorAreas
|
void GetElevatorAreas(handle table)
|
Fills table with a collection of areas reachable via elevator from this area. |
GetID
|
int GetID()
|
Get area ID. |
GetIncomingConnections
|
void GetIncomingConnections(ENavDirType dir, handle table)
|
Fills a passed in table with areas connected TO this area by a ONE-WAY link (ie: we have no connection back to them). |
GetParent
|
handle GetParent()
|
Returns the area just prior to this one in the search path. |
GetParentHow
|
int GetParentHow()
|
Returns how we get from parent to us. |
GetPlaceName
|
string GetPlaceName()
|
Get place name if it exists, null otherwise. |
GetPlayerCount
|
int GetPlayerCount(int team)
|
Return number of players of given team currently within this area (team of zero means any/all). |
GetRandomAdjacentArea
|
handle GetRandomAdjacentArea(int dir)
|
Return a random adjacent area in the given direction. |
GetSizeX
|
float GetSizeX()
|
Return the area size along the X axis. |
GetSizeY
|
float GetSizeY()
|
Return the area size along the Y axis. |
GetTravelDistanceToBombTarget
|
float GetTravelDistanceToBombTarget()
|
Gets the travel distance to the MvM bomb target. |
GetZ
|
float GetZ(Vector pos)
|
Return Z of area at (x,y) of 'pos' |
HasAttributeTF
|
bool HasAttributeTF(int bits)
|
Has TF-specific area attribute bits of the given ones. |
HasAttributes
|
bool HasAttributes(int bits)
|
Has area attribute bits of the given ones?. |
HasAvoidanceObstacle
|
bool HasAvoidanceObstacle(float maxheight)
|
Returns true if there's a large, immobile object obstructing this area |
IsBlocked
|
bool IsBlocked(int team, bool affectsFlow)
|
Return true if team is blocked in this area. |
IsBottleneck
|
bool IsBottleneck()
|
Returns true if area is a bottleneck. (tiny narrow areas with only one path) |
IsCompletelyVisibleToTeam
|
bool IsCompletelyVisibleToTeam(int team)
|
Return true if given area is completely visible from somewhere in this area by someone on the team. |
IsConnected
|
bool IsConnected(handle area, ENavDirType dir)
|
Return true if this area is connected to other area in given direction. (If you set direction to -1 or 4, it will automatically check all directions for a connection). |
IsCoplanar
|
bool IsCoplanar(handle area)
|
Return true if this area and given. area are approximately co-planar |
IsDamaging
|
bool IsDamaging()
|
Return true if this area is marked to have continuous damage. |
IsDegenerate
|
bool IsDegenerate()
|
Return true if this area is badly formed. |
IsEdge
|
bool IsEdge(ENavDirType dir)
|
Return true if there are no bi-directional links on the given side. |
IsFlat
|
bool IsFlat()
|
Return true if this area is approximately flat. |
IsOverlapping
|
bool IsOverlapping(handle area)
|
Return true if 'area' overlaps our 2D extents. |
IsOverlappingOrigin
|
bool IsOverlappingOrigin(Vector pos, float tolerance)
|
Return true if 'pos' is within 2D extents of area. |
IsPotentiallyVisibleToTeam
|
bool IsPotentiallyVisibleToTeam(int team)
|
Return true if any portion of this area is visible to anyone on the given team. |
IsReachableByTeam
|
bool IsReachableByTeam(int team)
|
Is this area reachable by the given team? |
IsRoughlySquare
|
bool IsRoughlySquare()
|
Return true if this area is approximately square. |
IsTFMarked
|
bool IsTFMarked()
|
Is this nav area marked with the current marking scope? |
IsUnderwater
|
bool IsUnderwater()
|
Return true if area is underwater. |
IsValidForWanderingPopulation
|
bool IsValidForWanderingPopulation()
|
Returns true if area is valid for wandering population. |
IsVisible
|
bool IsVisible(Vector point)
|
Return true if area is visible from the given eyepoint. |
MarkAsBlocked
|
void MarkAsBlocked(int team)
|
Mark this area as blocked for team. |
MarkAsDamaging
|
void MarkAsDamaging(float duration)
|
Mark this area is damaging for the next 'duration' seconds. |
MarkObstacleToAvoid
|
void MarkObstacleToAvoid(float height)
|
Marks the obstructed status of the nav area. |
RemoveAttributes
|
void RemoveAttributes(int bits)
|
Removes area attribute bits. |
RemoveOrthogonalConnections
|
void RemoveOrthogonalConnections(ENavDirType dir)
|
Removes all connections in directions to left and right of specified direction. |
SetAttributeTF
|
void SetAttributeTF(int bits)
|
Set TF-specific area attributes. |
SetAttributes
|
void SetAttributes(int bits)
|
Set area attribute bits. |
SetPlaceName
|
void SetPlaceName(string name)
|
Set place name. If you pass null, the place name will be set to nothing. |
TFMark
|
void TFMark()
|
Mark this nav area with the current marking scope. |
UnblockArea
|
void UnblockArea()
|
Unblocks this area. |
Game Instance: NavMesh
An interface to collect nav areas from, especially for pathfinding needs.
Methods
Function | Signature | Description |
---|---|---|
FindNavAreaAlongRay
|
handle FindNavAreaAlongRay(Vector startpos, Vector endpos, handle ignoreAreaID)
|
get nav area from ray |
GetAllAreas
|
void GetAllAreas(handle table)
|
fills a passed in table of all nav areas |
GetAreasWithAttributes
|
void GetAreasWithAttributes(int bits, handle table)
|
fills a passed in table of all nav areas that have the specified attributes |
GetNavArea
|
handle GetNavArea(Vector origin, float flBeneath)
|
given a position in the world, return the nav area that is closest to or below that height. |
GetNavAreaByID
|
handle GetNavAreaByID(int areaID)
|
get nav area by ID |
GetNavAreaCount
|
int GetNavAreaCount()
|
return total number of nav areas |
GetNavAreasFromBuildPath
|
bool GetNavAreasFromBuildPath(handle startArea, handle endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers, handle table)
|
Fills the table with areas from a path. Returns whether a path was found. If 'endArea' is NULL, will compute a path as close as possible to 'goalPos'. |
GetNavAreasInRadius
|
void GetNavAreasInRadius(Vector origin, float radius, handle table)
|
fills a passed in table of nav areas within radius |
GetNavAreasOverlappingEntityExtent
|
void GetNavAreasOverlappingEntityExtent(handle entity, handle table)
|
fills passed in table with areas overlapping entity's extent |
GetNearestNavArea
|
handle GetNearestNavArea(Vector origin, float maxDist, bool checkLOS, bool checkGround)
|
given a position in the world, return the nav area that is closest to or below that height. |
GetObstructingEntities
|
void GetObstructingEntities(handle table)
|
fills a passed in table of all obstructing entities |
NavAreaBuildPath
|
bool NavAreaBuildPath(handle startArea, handle endArea, Vector goalPos, float flMaxPathLength, int teamID, bool ignoreNavBlockers)
|
returns true if a path exists |
NavAreaTravelDistance
|
float NavAreaTravelDistance(handle startArea, handle endArea, float flMaxPathLength)
|
compute distance between two areas. Return -1 if can't reach 'endArea' from 'startArea' |
RegisterAvoidanceObstacle
|
void RegisterAvoidanceObstacle(handle entity)
|
registers avoidance obstacle |
UnregisterAvoidanceObstacle
|
void UnregisterAvoidanceObstacle(handle entity)
|
unregisters avoidance obstacle |
CNetPropManager
Game Instance: NetProps
Allows reading and updating the network properties and datamaps of an entity.
If the entity has multiple netprops with the same name, the data table name can be prepended with a dot to specify which one to use (e.g. "m_itTimer.m_timestamp").
- Interactive viewer of netprops: https://jackz.me/netprops/tf2
- Formatted list of netprops and datamaps: https://sigwiki.potato.tf/index.php/Entity_Properties
- Raw list of netprops and datamaps: https://www.invalidvertex.com/tf2dump.php
- Better raw list of datamaps that includes type information: https://cdn.discordapp.com/attachments/1039243316920844428/1095872595049599056/dump_datamaps.txt
EntityQuality
or AccountID
are banned and cannot be set nor fetched, to prevent spoofing economy items as legitimate.NetProps.GetPropInt
would simply become GetPropInt
.
foreach (k, v in ::NetProps.getclass())
if (k != "IsValid")
getroottable()[k] <- ::NetProps[k].bindenv(::NetProps);
Methods
Function | Signature | Description |
---|---|---|
GetPropArraySize
|
int GetPropArraySize(handle entity, string propertyName)
|
Returns the size of an netprop array, or -1. |
GetPropEntity
|
handle GetPropEntity(handle entity, string propertyName)
|
Reads an EHANDLE-valued netprop (21 bit integer). Returns the script handle of the entity. |
GetPropEntityArray
|
handle GetPropEntityArray(handle entity, string propertyName, int arrayElement)
|
Reads an EHANDLE-valued netprop (21 bit integer) from an array. Returns the script handle of the entity. |
GetPropBool
|
bool GetPropBool(handle entity, string propertyName)
|
Reads a boolean-valued netprop. |
GetPropBoolArray
|
bool GetPropBoolArray(handle entity, string propertyName, int arrayElement)
|
Reads a boolean-valued netprop from an array. |
GetPropFloat
|
float GetPropFloat(handle entity, string propertyName)
|
Reads a float-valued netprop. |
GetPropFloatArray
|
float GetPropFloatArray(handle entity, string propertyName, int arrayElement)
|
Reads a float-valued netprop from an array. |
GetPropInfo
|
bool GetPropInfo(handle entity, string propertyName, int arrayElement, handle table)
|
Fills in a passed table with property info for the provided entity. |
GetPropInt
|
int GetPropInt(handle entity, string propertyName)
|
Reads an integer-valued netprop. |
GetPropIntArray
|
int GetPropIntArray(handle entity, string propertyName, int arrayElement)
|
Reads an integer-valued netprop from an array. |
GetPropString
|
string GetPropString(handle entity, string propertyName)
|
Reads an string-valued netprop. |
GetPropStringArray
|
string GetPropStringArray(handle entity, string propertyName, int arrayElement)
|
Reads an string-valued netprop from an array. |
GetPropType
|
string GetPropType(handle entity, string propertyName)
|
Returns the name of the netprop type as a string. |
GetPropVector
|
Vector GetPropVector(handle entity, string propertyName)
|
Reads a 3D vector-valued netprop. |
GetPropVectorArray
|
Vector GetPropVectorArray(handle entity, string propertyName, int arrayElement)
|
Reads a 3D vector-valued netprop from an array. |
GetTable
|
void GetTable(handle entity, int iPropType, handle table)
|
Fills in a passed table with all props of a specified type for the provided entity (set iPropType to 0 for SendTable or 1 for DataMap) |
HasProp
|
bool HasProp(handle entity, string propertyName)
|
Checks if a netprop exists. |
SetPropBool
|
void SetPropBool(handle entity, string propertyName, bool value)
|
Sets a netprop to the specified boolean. |
SetPropBoolArray
|
void SetPropBoolArray(handle entity, string propertyName, bool value, int arrayElement)
|
Sets a netprop from an array to the specified boolean. |
SetPropEntity
|
void SetPropEntity(handle entity, string propertyName, handle value)
|
Sets an EHANDLE-valued netprop (21 bit integer) to reference the specified entity. |
SetPropEntityArray
|
void SetPropEntityArray(handle entity, string propertyName, handle value, int arrayElement)
|
Sets an EHANDLE-valued netprop (21 bit integer) from an array to reference the specified entity. |
SetPropFloat
|
void SetPropFloat(handle entity, string propertyName, float value)
|
Sets a netprop to the specified float. |
SetPropFloatArray
|
void SetPropFloatArray(handle entity, string propertyName, float value, int arrayElement)
|
Sets a netprop from an array to the specified float. |
SetPropInt
|
void SetPropInt(handle entity, string propertyName, int value)
|
Sets a netprop to the specified integer.
Предупреждение:Do not override
m_iTeamNum netprops on players or Engineer buildings permanently. Use ForceChangeTeam or SetTeam or respectively. Not doing so will result in unpredictable server crashes later on. Overriding m_iTeamNum temporarily and then reverting it in the same frame is safe however. |
SetPropIntArray
|
void SetPropIntArray(handle entity, string propertyName, int value, int arrayElement)
|
Sets a netprop from an array to the specified integer. |
SetPropString
|
void SetPropString(handle entity, string propertyName, string value)
|
Sets a netprop to the specified string. |
SetPropStringArray
|
void SetPropStringArray(handle entity, string propertyName, string value, int arrayElement)
|
Sets a netprop from an array to the specified string. |
SetPropVector
|
void SetPropVector(handle entity, string propertyName, Vector value)
|
Sets a netprop to the specified vector. |
SetPropVectorArray
|
void SetPropVectorArray(handle entity, string propertyName, Vector value, int arrayElement)
|
Sets a netprop from an array to the specified vector. |
CScriptEntityOutputs
Game Instance: EntityOutputs
Allows reading and manipulation of entity output data.
Methods
Function | Signature | Description |
---|---|---|
AddOutput
|
void AddOutput(handle entity, string outputName, string targetName, string inputName, string parameter, float delay, int timesToFire)
|
Adds a new output to the entity. |
GetNumElements
|
int GetNumElements(handle ntity entity, string outputName)
|
Returns the number of array elements. |
GetOutputTable
|
void GetOutputTable(handle entity, string outputName, table, int arrayElement)
|
Fills the passed table with output information. |
HasAction
|
bool HasAction(handle entity, string outputName)
|
Returns true if an action exists for the output. |
HasOutput
|
bool HasOutput(handle entity, string outputName)
|
Returns true if the output exists. |
RemoveOutput
|
void RemoveOutput(handle entity, string outputName, string targetName, string inputName, string parameter)
|
Removes an output from the entity. |
CScriptKeyValues
Script handle representation of a model's $keyvalues block. All sub-keys are instances of the same class.
Methods
Function | Signature | Description |
---|---|---|
constructor
| ||
FindKey
|
CScriptKeyValues FindKey(string key)
|
Find a sub key by the key name. |
GetFirstSubKey
|
CScriptKeyValues GetFirstSubKey()
|
Return the first sub key object. |
GetKeyBool
|
bool GetKeyBool(string key)
|
Return the key value as a bool. |
GetKeyFloat
|
float GetKeyFloat(string key)
|
Return the key value as a float. |
GetKeyInt
|
int GetKeyInt(string key)
|
Return the key value as an integer. |
GetKeyString
|
string GetKeyString(string key)
|
Return the key value as a string. |
GetNextKey
|
CScriptKeyValues GetNextKey()
|
Return the next neighbor key object to the one the method is called on. |
IsKeyEmpty
|
bool IsKeyEmpty(string key)
|
Returns true if the named key has no value. |
IsValid
|
bool IsValid()
|
Whether the handle belongs to a valid key. |
ReleaseKeyValues
|
void ReleaseKeyValues()
|
Releases the contents of the instance. |
CPlayerVoiceListener
Game Instance: PlayerVoiceListener
Tracks if any player is using voice and for how long.
Methods
Function | Signature | Description |
---|---|---|
GetPlayerSpeechDuration
|
float GetPlayerSpeechDuration(int playerIndex)
|
Returns the number of seconds the player has been continuously speaking. |
IsPlayerSpeaking
|
bool IsPlayerSpeaking(int playerIndex)
|
Returns whether the player specified is speaking. |
CEnvEntityMaker
Extends CBaseEntity
Script handle class for env entity maker .
Methods
Function | Signature | Description |
---|---|---|
SpawnEntity
|
void SpawnEntity()
|
Create an entity at the location of the maker |
SpawnEntityAtEntityOrigin
|
void SpawnEntityAtEntityOrigin(handle entity)
|
Create an entity at the location of a specified entity instance. |
SpawnEntityAtLocation
|
void SpawnEntityAtLocation(Vector origin, Vector orientation)
|
Create an entity at a specified location and orientation, orientation is Euler angle in degrees (pitch, yaw, roll). |
SpawnEntityAtNamedEntityOrigin
|
void SpawnEntityAtNamedEntityOrigin(string targetname)
|
Create an entity at the location of a named entity. If multiple entities have the same name, only the one with the lowest entity index will be targeted. |
CPointTemplate
Extends CBaseEntity
Script handle class for point_template.
Hooks
table PreSpawnInstance(string entityClass, string entityName)
- If this is defined, it will be called right before the entity is created, and any keyvalues returned will be assigned to the entity.
function PreSpawnInstance( entityClass, entityName )
{
local keyvalues =
{
rendercolor = "0 255 0",
targetname = "mySpawnedEntity"
}
return keyvalues
}
void PostSpawn(table entities)
- Called after the entities are spawned. A table with the handles of the spawned entities indexed by name is passed to the function. Could use this to connect outputs or do whatever needs to be done after the entity was created.
function PostSpawn( entities )
{
foreach( targetname, handle in entities )
{
printl( targetname + ": " + handle )
}
}
Example
Spawned entities can be accessed synchronously in script by using an entity maker. The following generalised example creates a global SpawnMyEntity()
function which spawns and returns the templated entity. It can be modified to support multiple templated entities.
m_hSpawnedEntity <- null;
m_KeyValues <- null;
m_hSpawner <- Entities.CreateByClassname( "env_entity_maker" );
m_hSpawner.__KeyValueFromString( "EntityTemplate", self.GetName() );
function PreSpawnInstance( classname, targetname )
{
return m_KeyValues;
}
function PostSpawn( entities )
{
foreach ( targetname, entity in entities )
{
m_hSpawnedEntity = entity;
break;
}
}
::SpawnMyEntity <- function( keyvalues = null )
{
m_KeyValues = keyvalues;
m_hSpawner.SpawnEntity();
return m_hSpawnedEntity;
}.bindenv(this)
Spawn templated entities from any script.
local ent = SpawnMyEntity( {
rendercolor = Vector( RandomInt(0, 255), RandomInt(0, 255), RandomInt(0, 255) )
} )
printl( ent )
CFuncTrackTrain
Extends CBaseEntity
Script handle class for func_tracktrain.
Methods
Function | Signature | Description |
---|---|---|
GetFuturePosition
|
Vector GetFuturePosition(float x, float speed)
|
Get a position on the track X seconds in the future. |
CPointScriptTemplate
Extends CBaseEntity
Script handle class for point_script_template.
Methods
Function | Signature | Description |
---|---|---|
AddTemplate
|
void AddTemplate(string, table)
|
Add an entity to the template spawner |
SetGroupSpawnTables
|
void SetGroupSpawnTables(table)
|
Cache the group spawn tables |
CSceneEntity
Extends CBaseEntity
Script handle class for scripted_scene, which make use of VCD data.
Methods
Function | Signature | Description |
---|---|---|
AddBroadcastTeamTarget
|
void AddBroadcastTeamTarget(int index)
|
Adds a team (by index) to the broadcast list. |
EstimateLength
|
float EstimateLength()
|
Returns length of this scene in seconds. |
FindNamedEntity
|
handle FindNamedEntity(string reference)
|
Given an entity reference, such as !target, get actual entity from scene object |
IsPaused
|
bool IsPaused()
|
If this scene is currently paused. |
IsPlayingBack
|
bool IsPlayingBack()
|
If this scene is currently playing. |
LoadSceneFromString
|
bool LoadSceneFromString(string sceneName, string scene)
|
Given a dummy scene name and a vcd string, load the scene. |
RemoveBroadcastTeamTarget
|
void RemoveBroadcastTeamTarget(int index)
|
Removes a team (by index) from the broadcast list. |
CCallChainer
CCallChainer objects collect all functions with a matching prefix in a given scope, then inserts it all into the chains
table with the prefix removed. All collected unprefixed functions can then be called in a chain using the class's Call()
method, given the method's event argument matches the functions' name.
Whenever a CCallChainer object is created, a function named Dispatch
followed by its given prefix will also be created, which the class binds the environment of its Call()
method to.
Methods
Function | Signature | Description |
---|---|---|
constructor
|
CCallChainer(string functionPrefix, table scope = null)
|
Creates a CCallChainer object that'll collect functions that have a matching prefix in the given scope. |
PostScriptExecute
|
void PostScriptExecute()
|
Search for all non-native functions with matching prefixes, then push them into the chains table.
|
Call
|
bool Call(string event, any ...)
|
Find an unprefixed function name in the chains table and call it with the given arguments.
|
Members
Instance | Type | Description |
---|---|---|
chains
|
table
|
Contains names of unprefixed functions, each with an array of functions to call. |
prefix
|
string
|
Prefix that functions should have to be added into the chains table. Set by the constructor.
|
scope
|
table
|
If set, seek functions in this scope instead. Set by the constructor. |
CSimpleCallChainer
Intended to be simpler to use than CCallChainer, the class CSimpleCallChainer holds only a single chain of functions inside an array instead of multiple inside a table. As such, its Call()
method does not need a function's name.
This class is also used internally by these CBaseEntity hooks: Precache()
and OnPostSpawn()
.
Methods
Function | Signature | Description |
---|---|---|
constructor
|
CSimpleCallChainer(string functionPrefix, table scope = null, exactMatch = false)
|
Creates a CSimpleCallChainer object that'll collect functions that have a matching prefix in the given scope, unless it seek for an exact name match. |
PostScriptExecute
|
void PostScriptExecute()
|
Begin searching for all non-native functions with matching prefixes, then push them into the chain array.
|
Call
|
bool Call(any ...)
|
Call all functions inside the chain array with the given arguments.
|
Members
Instance | Type | Description |
---|---|---|
chain
|
array
|
All functions to be called by the Call() method.
|
exactMatch
|
bool
|
If set, names of non-native functions and prefix must be an exact match. Set by the constructor.
|
prefix
|
string
|
Prefix that functions should have to be added into the chain array. Set by the constructor.
|
scope
|
table
|
If set, seek functions in this scope instead. Set by the constructor. |
NextBotCombatCharacter
Extends CBaseCombatCharacter
Script handle class for non-playable combat characters operating under the NextBot system.
Methods
Function | Signature | Description |
---|---|---|
ClearImmobileStatus
|
void ClearImmobileStatus()
|
Clear immobile status |
FlagForUpdate
|
void FlagForUpdate(bool toggle)
|
Flag this bot for update |
GetBodyInterface
|
INextBotComponent GetBodyInterface()
|
Get this bot's body interface |
GetBotId
|
int GetBotId()
|
Get this bot's id |
GetImmobileDuration
|
float GetImmobileDuration()
|
How long have we been immobile |
GetImmobileSpeedThreshold
|
float GetImmobileSpeedThreshold()
|
Return units/second below which this actor is considered immobile |
GetIntentionInterface
|
INextBotComponent GetIntentionInterface()
|
Get this bot's intention interface |
GetLocomotionInterface
|
ILocomotion GetLocomotionInterface()
|
Get this bot's locomotion interface |
GetTickLastUpdate
|
int GetTickLastUpdate()
|
Get last update tick |
GetVisionInterface
|
INextBotComponent GetVisionInterface()
|
Get this bot's vision interface |
IsEnemy
|
bool IsEnemy(handle entity)
|
Return true if given entity is our enemy |
IsFlaggedForUpdate
|
bool IsFlaggedForUpdate()
|
Is this bot flagged for update |
IsFriend
|
bool IsFriend(handle entity)
|
Return true if given entity is our friend |
IsImmobile
|
bool IsImmobile()
|
Return true if we haven't moved in awhile |
INextBotComponent
Base script handle class for any interfaces belonging to an individual NextBotCombatCharacter entity.
Methods
Function | Signature | Description |
---|---|---|
ComputeUpdateInterval
|
bool ComputeUpdateInterval()
|
Recomputes the component update interval |
GetUpdateInterval
|
float GetUpdateInterval()
|
Returns the component update interval |
Reset
|
void Reset()
|
Resets the internal update state |
ILocomotion
Extends INextBotComponent
The interface for interacting with a specific NextBot's movement brain.
Methods
Function | Signature | Description |
---|---|---|
Approach
|
void Approach(Vector goal, float goalWeight)
|
The primary locomotive method. Goal determines the destination position to move towards. goalWeight determines the priority of this path, you can set this to 1.0 generally speaking.
Совет:To make the entity move smoothly towards its destination make sure to put this under a think function.
|
ClearStuckStatus
|
void ClearStuckStatus(string reason)
|
Reset stuck status to un-stuck. Reason message is shown when debugging nextbots. |
ClimbUpToLedge
|
bool ClimbUpToLedge(Vector goalPos, Vector goalForward, handle obstacle)
|
Initiate a jump to an adjacent high ledge, return false if climb can't start |
ComputeUpdateInterval
|
bool ComputeUpdateInterval()
|
Returns false if no time has elapsed |
DriveTo
|
void DriveTo(Vector pos)
|
Move the bot to the precise given position immediately, updating internal state |
FaceTowards
|
void FaceTowards(Vector target)
|
Rotate body to face towards target
Совет:To make the entity look smoothly towards a spot make sure to put this under a think function, as using the function only once makes the entity only look towards it a bit but not fully, rotating ever so slightly.
|
FractionPotentialGap
|
float FractionPotentialGap(Vector from, Vector to)
|
If the locomotor cannot jump over the gap, returns the fraction of the jumpable ray |
FractionPotentiallyTraversable
|
float FractionPotentiallyTraversable(Vector from, Vector to, bool immediately)
|
If the locomotor could not move along the line given, returns the fraction of the walkable ray. If immediately is true, breakables are considered non-traverseable |
GetDeathDropHeight
|
float GetDeathDropHeight()
|
Distance at which we will die if we fall |
GetDesiredSpeed
|
float GetDesiredSpeed()
|
Get desired speed for locomotor movement |
GetFeet
|
Vector GetFeet()
|
Return position of feet - the driving point where the bot contacts the ground |
GetGround
|
handle GetGround()
|
Return the current ground entity or NULL if not on the ground |
GetGroundMotionVector
|
Vector GetGroundMotionVector()
|
Return unit vector in XY plane describing our direction of motion - even if we are currently not moving |
GetGroundNormal
|
Vector GetGroundNormal()
|
Surface normal of the ground we are in contact with |
GetGroundSpeed
|
float GetGroundSpeed()
|
Return current world space speed in XY plane |
GetMaxAcceleration
|
float GetMaxAcceleration()
|
Return maximum acceleration of locomotor |
GetMaxDeceleration
|
float GetMaxDeceleration()
|
Return maximum deceleration of locomotor |
GetMaxJumpHeight
|
float GetMaxJumpHeight()
|
Return maximum height of a jump.
Совет:If using a
base_boss entity, as there is currently no available method to modify this value, you can fire the input SetMaxJumpHeight to change it. |
GetMotionVector
|
Vector GetMotionVector()
|
Return unit vector describing our direction of motion - even if we are currently not moving |
GetRunSpeed
|
float GetRunSpeed()
|
Get maximum running speed |
GetSpeed
|
float GetSpeed()
|
Return current world space speed (magnitude of velocity) |
GetSpeedLimit
|
float GetSpeedLimit()
|
Get maximum speed bot can reach, regardless of desired speed |
GetStepHeight
|
float GetStepHeight()
|
If delta Z is lower than this, we can step up the surface (like a stair step), but if delta Z is greater than this, we have to jump to get up.
Совет:If using a
base_boss entity, as there is currently no available method to modify this value, you can fire the input SetStepHeight to change it. |
GetStuckDuration
|
float GetStuckDuration()
|
Return how long we've been stuck |
GetTraversableSlopeLimit
|
float GetTraversableSlopeLimit()
|
Return Z component of unit normal of steepest traversable slope |
GetUpdateInterval
|
float GetUpdateInterval()
|
Returns time between updates |
GetVelocity
|
Vector GetVelocity()
|
Return current world space velocity |
GetWalkSpeed
|
float GetWalkSpeed()
|
Get maximum walking speed |
HasPotentialGap
|
float HasPotentialGap(Vector from, Vector to)
|
Checks if there is a possible gap that will need to be jumped over. Returns fraction of ray from 0 to 1. |
IsAbleToClimb
|
bool IsAbleToClimb()
|
Return true if this bot can climb arbitrary geometry it encounters |
IsAbleToJumpAcrossGaps
|
bool IsAbleToJumpAcrossGaps()
|
Return true if this bot can jump across gaps in its path |
IsAreaTraversable
|
bool IsAreaTraversable(handle area)
|
Return true if given area can be used for navigation |
IsAttemptingToMove
|
bool IsAttemptingToMove()
|
Return true if we have tried to Approach() or DriveTo() very recently |
IsClimbingOrJumping
|
bool IsClimbingOrJumping()
|
Is jumping in any form |
IsClimbingUpToLedge
|
bool IsClimbingUpToLedge()
|
Is climbing up to a high ledge |
IsEntityTraversable
|
bool IsEntityTraversable(handle entity, bool immediately)
|
Return true if the entity handle is traversable. If immediately is true, breakables are considered non-traverseable |
IsGap
|
bool IsGap(Vector pos, Vector forward)
|
Return true if there is a gap at this position.
Примечание:forward is unused.
|
IsJumpingAcrossGap
|
bool IsJumpingAcrossGap()
|
Is jumping across a gap to the far side |
IsOnGround
|
bool IsOnGround()
|
Return true if standing on something |
IsPotentiallyTraversable
|
float IsPotentiallyTraversable(Vector from, Vector to, bool immediately)
|
Checks if this locomotor could potentially move along the line given. Returns fraction of trace result (1 = clear). If immediately is true, breakables are considered non-traverseable |
IsRunning
|
bool IsRunning()
|
Is running? |
IsScrambling
|
bool IsScrambling()
|
Is in the middle of a complex action (climbing a ladder, climbing a ledge, jumping, etc) that shouldn't be interrupted |
IsStuck
|
bool IsStuck()
|
Return true if bot is stuck. If the locomotor cannot make progress, it becomes stuck and can only leave this stuck state by successfully movingand becoming un-stuck. |
Jump
|
void Jump()
|
Initiate a simple undirected jump in the air |
JumpAcrossGap
|
void JumpAcrossGap(Vector goalPos, Vector goalForward)
|
Initiate a jump across an empty volume of space to far side
Примечание:goalForward is unused.
|
OnLandOnGround
|
void OnLandOnGround(handle ground)
|
Manually run the OnLandOnGround callback. Typically invoked when bot lands on the ground after being in the air |
OnLeaveGround
|
void OnLeaveGround(handle ground)
|
Manually run the OnLeaveGround callback. Typically invoked when bot leaves ground for any reason |
Reset
|
void Reset()
|
Resets motion, stuck state etc |
Run
|
void Run()
|
Set desired movement speed to running |
SetDesiredSpeed
|
void SetDesiredSpeed(float speed)
|
Set desired speed for locomotor movement |
SetSpeedLimit
|
void SetSpeedLimit(float limit)
|
Set maximum speed bot can reach, regardless of desired speed |
Stop
|
void Stop()
|
Set desired movement speed to stopped |
Walk
|
void Walk()
|
Set desired movement speed to walking |
LateBinder
Methods
Function | Signature | Description |
---|---|---|
Begin
|
||
End
|
||
EstablishDelegation
|
||
HookRootMetamethod
|
||
UnhookRootMetamethod
|
||
RemoveDelegation
|
||
Resolve
|
Members
Instance | Type | Description |
---|---|---|
m_bindNamesStack
|
array
|
|
m_fixupSet
|
array
|
|
m_log
|
bool
|
|
m_logIndent
|
int
|
|
m_targetTable
|
table?(null)
|
regexp
The built-in Squirrel class for regular expressions.
Methods
Function | Signature | Description |
---|---|---|
constructor
|
regexp()
|
|
capture
|
table capture(str, [start])
|
Returns an array of tables containing two indexes ("begin" and "end") of the first match of the regular expression in the string str. An array entry is created for each captured sub expressions. If no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string. |
match
|
bool match(str)
|
Returns a true if the regular expression matches the string str, otherwise returns false. |
search
|
table search(str, [start])
|
Returns a table containing two indexes ("begin" and "end") of the first match of the regular expression in the string str, otherwise if no match occurs returns null. The search starts from the index start of the string, if start is omitted the search starts from the beginning of the string. |
subexpcount
|
subexpcount()
|
Типы данных
Vector
Эквивалент класса Vector из С++. Трёхмерный вектор с перегруженными арифметическими операциями для векторов и скалярных величин.
Методы
Функция | Написание | Описание |
---|---|---|
constructor
|
Vector(float x = 0, float y = 0, float z = 0)
|
Creates a new vector with the specified Cartesian coordiantes. |
Cross
|
Vector Cross(Vector factor)
|
The vector product of two vectors. Returns a vector orthogonal to the input vectors. |
Dot
|
float Dot(Vector factor)
|
The scalar product of two vectors. |
Length
|
float Length()
|
Magnitude of the vector. |
LengthSqr
|
float LengthSqr()
|
The magnitude of the vector squared. Faster than the above method.
Совет:This can be used to quickly check if the vector is equal to 0 0 0, by checking if the magnitude is 0.
|
Length2D
|
float Length2D()
|
Returns the magnitude of the vector on the x-y plane. Meant to be used when working with the client's HUD. |
Length2DSqr
|
float Length2DSqr()
|
Returns the square of the magnitude of the vector on the x-y plane. Faster than the above method. |
Norm
|
float Norm()
|
Normalizes the vector in place and returns it's length. |
Scale
|
Vector Scale(float factor)
|
Scales the vector magnitude. |
ToKVString
|
string ToKVString()
|
Returns a string without separations commas. |
tostring
|
string tostring()
|
Returns a human-readable string. |
Участники
Instance | Type | Description |
---|---|---|
x
|
float
|
Cartesian X axis. |
y
|
float
|
Cartesian Y axis. |
z
|
float
|
Cartesian Z axis. |
Operations
Operation | Return Type | Description |
---|---|---|
Vector + Vector
|
Vector
|
Returns the sum of both classes's members (XYZ). |
QAngle + Vector
| ||
Vector - Vector
|
Vector
|
Returns the subtraction of both classes's members (XYZ). |
QAngle + Vector
| ||
Vector * integer
|
Vector
|
Returns the multiplication of a Vector against a scalar. |
Vector * float
|
QAngle
Эквивалент класса QAngle из С++. Представляет собой трёхмерную ориентацию в качестве углов Эйлера.
Имеет перегруженные арифметические операции, как для QAngles, так и для скалярных величин.
Методы
Функция | Написание | Описание |
---|---|---|
constructor
|
QAngle(float pitch = 0, float yaw = 0, float roll = 0)
|
Creates a new QAngle. |
Forward
|
Vector Forward()
|
Returns the Forward Vector of the angles. |
Left
|
Vector Left()
|
Returns the left Vector of the angles. |
Pitch
|
float Pitch()
|
Returns the pitch angle in degrees. |
Roll
|
float Roll()
|
Returns the roll angle in degrees. |
ToKVString
|
string ToKVString()
|
Returns a string with the values separated by one space. |
ToQuat
|
Quaternion ToQuat()
|
Returns a quaternion representaion of the orientation. |
Up
|
Vector Up()
|
Returns the Up Vector of the angles. |
Yaw
|
float Yaw()
|
Returns the yaw angle in degrees. |
Участники
Instance | Type | Description |
---|---|---|
x
|
float
|
Pitch in degrees. |
y
|
float
|
Yaw in degrees. |
z
|
float
|
Roll in degrees. |
Операции
Operation | Return Type | Description |
---|---|---|
QAngle + QAngle
|
QAngle
|
Sum of both classes's members (XYZ). |
Vector + QAngle
| ||
QAngle - QAngle
|
QAngle
|
Subtraction of both classes's members (XYZ). |
Vector - QAngle
| ||
QAngle * int
|
QAngle
|
QAngle multiplied by a number. |
QAngle * float
|
Vector2D, Vector4D
Двух и четырёхмерные эквиваленты Vector'a.
Методы
Функция | Написание | Описание |
---|---|---|
constructor
|
VectorXD(float x, float y, ...)
|
Creates a new vector with the specified Cartesian coordiantes. |
Dot
|
float Dot(VectorXD factor)
|
The scalar product of two vectors. |
Length
|
float Length()
|
Magnitude of the vector. |
LengthSqr
|
float LengthSqr()
|
The magnitude of the vector squared. Faster than the above method. |
Norm
|
float Norm()
|
Seems to also return the vector length. |
ToKVString
|
string ToKVString()
|
Returns a string without separations commas. |
Кватернион
Кватернион представляет собой повороты в трёхмерном пространстве.
Методы
Function | Signature | Description |
---|---|---|
constructor
|
Quaternion()
|
Creates a new identity quaternion. |
constructor
|
Quaternion(float x,float y,float z,float w)
|
Creates a new quaternion of the form w + xi + yj + zk .
|
Dot
|
float Dot(Quaternion factor)
|
The 4D scalar product of two quaternions. represents the angle between the quaternions in the range [1, 0]. |
Invert
|
Quaternion Invert()
|
Returns a quaternion with the complimentary rotation. |
Norm
|
float Norm()
|
Normalizes the quaternion. |
SetPitchYawRoll
|
void SetPitchYawRoll(float pitch, float yaw, float roll)
|
Recomputes the quaternion from the supplied Euler angles. |
ToKVString
|
string ToKVString()
|
Returns a string with the values separated by one space. |
ToQAngle
|
QAngle ToQAngle()
|
Returns the angles resulting from the rotation. |
Участники
Экземпляр | Тип | Описание |
---|---|---|
x
|
float
|
Vector component along the i axis. |
y
|
float
|
Vector component along the j axis. |
z
|
float
|
Vector component along the k axis. |
w
|
float
|
Scalar part. |
Операции
Операция | Тип вывода | Описание |
---|---|---|
Quaternion + Quaternion
|
Quaternion
|
Sum of the two Quaternions. |
Quaternion - Quaternion
|
Quaternion
|
Subtraction of the two Quaternions. |
Quaternion * integer
|
Quaternion
|
Quaternion multiplied by a number. |
Quaternion * float
|
Глобальные
Функция | Написание | Описание |
---|---|---|
AddThinkToEnt
|
void AddThinkToEnt(handle entity, string FuncName)
|
Sets a function in the entity's script to rerun by itself constantly. Pass null as the function name to remove a think function. The default think interval is 0.1s, unless overridden by returning a different time interval in seconds in the think function
Совет:Return -1 to think every tick. Do not return 0, this will give inconsistent intervals.
Подтвердить:This issue has only been observed on players Примечание:If trying to clear a think function while inside a think function, this function alone will not work as the think function is restored on the entity after it's finished.
NetProps.SetPropString(self, "m_iszScriptThinkFunction", ""); must be used to fully clear the think function.
Предупреждение:This can apply to events if they are chained from a think function, for example killing a player with TakeDamage and then trying to clear the think function in player_death event. The think function will not be cleared unless the line above is also added.Примечание:Adding a think function will clear the
EFL_NO_THINK_FUNCTION eflag, but the eflag can be added afterwards and the script think will still work.Баг:The think function name stored in the entity is not reset if null is passed as the function name. However this is harmless, and it will only show a warning in console. [todo tested in?] |
AddToScriptHelp
|
AddToScriptHelp()
|
|
AllowThirdPersonCamera
|
bool AllowThirdPersonCamera()
|
|
ArePlayersInHell
|
bool ArePlayersInHell()
|
|
Assert
|
void Assert(bool value, string optional message)
|
Test value and if not true, throws exception, optionally with message. |
ClearGameEventCallbacks
|
void ClearGameEventCallbacks()
|
Empties the tables of game event callback functions. |
CreateProp
|
handle CreateProp(string classname, Vector origin, string model_name, int activity)
|
Create a prop |
CreateSceneEntity
|
handle CreateSceneEntity(string scene)
|
Create a scene entity to play the specified scene. |
developer
|
int developer()
|
The current level of the developer console variable.
|
DispatchParticleEffect
|
void DispatchParticleEffect(string name, Vector origin, Vector angles)
|
Dispatches a one-off particle system Баг:The angles parameter is incorrectly defined as a Vector type rather than QAngle. [todo tested in?] Предупреждение:This does not precache the particle! As a result, custom particles may show as a burst of red Xs instead. To precache a particle, use the following function:
function PrecacheParticle(name)
{
PrecacheEntityFromTable({ classname = "info_particle_system", effect_name = name })
}
Примечание:To spawn particles that require to be tied to an entity, or require following a specific attachment, use a trigger particle entity. Example:
local entity = GetListenServerHost();
local particle_name = entity.GetTeam() == 2 ? "spy_start_disguise_red" : "spy_start_disguise_blue";
local particle = SpawnEntityFromTable("trigger_particle",
{
particle_name = particle_name,
attachment_type = 1, // PATTACH_ABSORIGIN_FOLLOW,
spawnflags = 64 // allow everything
});
EntFireByHandle(particle, "StartTouch", "!activator", -1, entity, entity);
EntFireByHandle(particle, "Kill", "", -1, null, null);
|
Document
|
void Document(unknown symbolOrTable, unknown itemIfSymbol = null, string descriptionIfSymbol = null)
| |
DoEntFire
|
void DoEntFire(string target, string action, string value, float delay, handle activator, handle caller)
|
Generate an entity I/O event. The caller and activator argument takes a CBaseEntity script handle, and entities assigned can receive inputs with target set to !self, or !activator / !caller.
Совет:Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.
Примечание:Does not work if the target string is
point_servercommand . |
DoIncludeScript
|
bool DoIncludeScript(string file, handle/table scope)
|
Execute a script. and put all its content for the argument passed to thescope parameter. (internal)
|
IncludeScript
|
bool IncludeScript(string file, handle scope = null)
|
Wrapper for DoIncludeScript |
EmitAmbientSoundOn
|
void EmitAmbientSoundOn(string soundName, float volume, int soundlevel, int pitch, handle entity)
|
Play named sound on an entity using configurations similar to ambient generic . Soundlevel is in decibels, see this page for real world equivalents.
Совет:Sounds may be hard to hear even at full volume. Naming custom sounds according to the soundmixer can be used to make them naturally louder.
Совет:To convert radius in Hammer units to decibels (similar to ambient generic ), use the following formula:
local soundlevel = (40 + (20 * log10(radius / 36.0))).tointeger();
|
StopAmbientSoundOn
|
void StopAmbientSoundOn(string soundName, handle entity)
|
Stop named sound on an entity using configurations similar to ambient generic . |
EmitSoundEx
|
void EmitSoundEx(handle table)
|
Play a sound. Takes in a script table of params: sound_name , channel , volume , sound_level , flags , pitch , special_dsp , origin , delay , sound_time , entity , speaker_entity , filter_type , filter_param . All parameters are optional except sound_name. See the main page for more details.
|
EmitSoundOn
|
void EmitSoundOn(string soundScript, handle entity)
|
Play named sound on Entity. Legacy only, use EmitSoundEx. |
StopSoundOn
|
void StopSoundOn(string soundScript, handle entity)
|
Stop named sound on an entity. |
EmitSoundOnClient
|
void EmitSoundOnClient(string soundScript, handle player)
|
Play named sound only on the client for the specified player. NOTE: This only supports soundscripts. Legacy only, use EmitSoundEx. |
EntFire
|
void EntFire(string target, string action, string value = null, float delay = 0, handle activator = null)
|
Wrapper for DoEntFire() that setsactivator to null, but has nocaller param.
Совет:Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.
Примечание:Does not work if the target string is
point_servercommand . |
EntFireByHandle
|
void EntFireByHandle(handle entity, string action, string value, float delay, handle activator, handle caller)
|
Generate an entity i/o event. First parameter is an entity instance.
Совет:Use a -1 delay to consistently fire it at the end of the frame. 0 delay might bring inconsistent timing.
|
EntIndexToHScript
|
handle EntIndexToHScript(int entIndex)
|
Turn an entity index integer to an HScript representing that entity's script instance. |
FileToString
|
string FileToString(string file)
|
Reads a string from file located in the game's scriptdata folder. Returns the string from the file, null if no file or file is greater than 16384 bytes.
Примечание:Files packed inside the BSP cannot be read.
Примечание:This opens files in text mode, therefore binary files will not be parsed correctly.
|
FindCircularReference
|
FindCircularReference()
|
|
FindCircularReferences
|
FindCircularReferences()
|
|
FireGameEvent
|
bool FireGameEvent(string name, handle table)
|
Fire a game event to a listening callback function in script. Parameters are passed in a squirrel table.
Примечание:The name might be misleading. This does not fire an event that the game will pick up, the function that sends a real game event is named
SendGlobalGameEvent . |
FireScriptHook
|
bool FireScriptHook(string name, handle table)
|
Fire a script hook to a listening callback function in script. Parameters are passed in a squirrel table. |
FireScriptEvent
|
void FireScriptEvent(string event, table params)
|
Wrapper for __RunEventCallbacks()
|
ForceEnableUpgrades
|
void ForceEnableUpgrades(int state)
|
Whether to force on MvM-styled upgrades on/off. 0 -> default, 1 -> force off, 2 -> force on |
ForceEscortPushLogic
|
void ForceEscortPushLogic(int state)
|
Forces payload pushing logic. 0 -> default, 1 -> force off, 2 -> force on |
FlagsMayBeCapped
|
bool FlagsMayBeCapped()
|
May a flag be captured? |
FrameTime
|
float FrameTime()
|
Get the time spent on the server in the last frame |
GameModeUsesCurrency
|
bool GameModeUsesCurrency()
|
Does the current gamemode have currency? |
GameModeUsesMiniBosses
|
bool GameModeUsesMiniBosses()
|
Does the current gamemode have minibosses? |
GameModeUsesUpgrades
|
bool GameModeUsesUpgrades()
|
Does the current gamemode have upgrades? |
GetClassLimit
|
int GetClassLimit(int class)
|
Get class limit for class. See Constants.ETFClass. |
GetDeveloperLevel
|
int GetDeveloperLevel()
|
Gets the level of 'developer' |
GetFrameCount
|
int GetFrameCount()
|
Returns the engines current frame count |
GetFriction
|
float GetFriction(handle player)
|
Returns the Friction on a player entity, meaningless if not a player |
GetFunctionSignature
|
string GetFunctionSignature(function func, string prefix)
|
|
GetGravityMultiplier
|
float GetGravityMultiplier()
|
|
GetListenServerHost
|
handle GetListenServerHost()
|
Get the local player on a listen server. |
GetMannVsMachineAlarmStatus
|
bool GetMannVsMachineAlarmStatus()
|
|
GetMapName
|
string GetMapName()
|
Get the name of the map. |
GetModelIndex
|
int GetModelIndex(string filename)
|
Returns the index of the named model. |
GetOvertimeAllowedForCTF
|
bool GetOvertimeAllowedForCTF()
|
|
GetPhysAngularVelocity
|
Vector GetPhysAngularVelocity(handle entity)
|
Returns the Angular velocity of the entity. Deprecated, use the GetPhysAngularVelocity method on the entity instead.
|
GetPhysVelocity
|
Vector GetPhysVelocity(handle entity)
|
Returns the velocity of the entity. Deprecated, use the GetPhysVelocity method on the entity instead.
|
GetPlayerFromUserID
|
handle GetPlayerFromUserID(int userid)
|
Given a user id, return the entity, or null.
Примечание:The 'fake' SourceTV player will always be returned as null.
|
GetRoundState
|
int GetRoundState()
|
Get current round state. See Constants.ERoundState. |
GetSoundDuration
|
float GetSoundDuration(string soundname, string actormodelname)
|
Returns float duration of the sound. Actor model name is optional and can be left null.
Нужно сделать: Actor model name is likely a leftover from Half-Life 2
Предупреждение:Does not work on dedicated servers as they do not have audio libraries built-in to load sounds.
|
GetStopWatchState
|
int GetStopWatchState()
|
Get the current stopwatch state. See Constants.EStopwatchState. |
GetWinningTeam
|
int GetWinningTeam()
|
Who won! |
HaveStopWatchWinner
|
bool HaveStopWatchWinner()
|
|
InMatchStartCountdown
|
bool InMatchStartCountdown()
|
Are we in the pre-match/setup state? |
InOvertime
|
bool InOvertime()
|
Currently in overtime? |
IsAttackDefenseMode
|
bool IsAttackDefenseMode()
|
|
IsBirthday
|
bool IsBirthday()
|
Are we in birthday mode? |
IsCompetitiveMode
|
bool IsCompetitiveMode()
|
Playing competitive? |
IsDedicatedServer
|
bool IsDedicatedServer()
|
Returns true if this server is a dedicated server. |
IsDefaultGameMode
|
bool IsDefaultGameMode()
|
The absence of arena, mvm, tournament mode, etc |
IsHolidayActive
|
bool IsHolidayActive(int holiday)
|
Is the given holiday active? See Constants.EHoliday. |
IsHolidayMap
|
bool IsHolidayMap(int holiday)
|
Playing a holiday map? See Constants.EHoliday. |
IsInArenaMode
|
bool IsInArenaMode()
|
Playing arena mode? |
IsInKothMode
|
bool IsInKothMode()
|
Playing king of the hill mode? |
IsInMedievalMode
|
bool IsInMedievalMode()
|
Playing medieval mode? |
IsInWaitingForPlayers
|
bool IsInWaitingForPlayers()
|
Are we waiting for some stragglers? |
IsMannVsMachineMode
|
bool IsMannVsMachineMode()
|
Playing MvM? Beep boop |
IsMannVsMachineRespecEnabled
|
bool IsMannVsMachineRespecEnabled()
|
Are players allowed to refund their upgrades? |
IsMatchTypeCasual
|
bool IsMatchTypeCasual()
|
Playing casual? |
IsMatchTypeCompetitive
|
bool IsMatchTypeCompetitive()
|
Playing competitive? |
IsModelPrecached
|
bool IsModelPrecached(string modelname)
|
Checks if the modelname is precached. |
IsSoundPrecached
|
bool IsSoundPrecached(string soundname)
|
Checks if the soundname is precached. |
IsPasstimeMode
|
bool IsPasstimeMode()
|
No ball games. |
IsPlayerABot
|
bool IsPlayerABot(handle player)
|
Is this player/entity a bot. |
IsPowerupMode
|
bool IsPowerupMode()
|
Playing powerup mode? Not compatible with MvM |
IsPVEModeActive
|
bool IsPVEModeActive()
|
|
IsQuickBuildTime
|
bool IsQuickBuildTime()
|
If an engie places a building, will it immediately upgrade? Eg. MvM pre-round etc. |
IsTruceActive
|
bool IsTruceActive()
|
|
IsUsingGrapplingHook
|
bool IsUsingGrapplingHook()
|
|
IsUsingSpells
|
bool IsUsingSpells()
|
|
IsWeakref
|
bool IsWeakref()
|
|
LocalTime
|
void LocalTime(table out)
|
Fills out a table with the local time (second, minute, hour, day, month, year, dayofweek, dayofyear, daylightsavings) |
MakeNamespace
|
MakeNamespace()
|
|
MapHasMatchSummaryStage
|
bool MapHasMatchSummaryStage()
|
|
MatchmakingShouldUseStopwatchMode
|
bool MatchmakingShouldUseStopwatchMode()
|
|
MaxClients
|
float MaxClients()
|
Get the current number of max clients set by the maxplayers command.
Баг:The return value is mistakenly defined as a float. It is best to use .tointeger() after calling this. [todo tested in?] |
PickupObject
|
void PickupObject(handle player, handle entity)
|
Object from world is put into the "Held" slot of the player. Warning: it will smoothly interpolate from where it is to the players hand - which is a bit goofy if it is on other side of level.
Примечание:Does nothing in Team Fortress 2 as the code is not implemented.
|
PlayerInstanceFromIndex
|
CBasePlayer PlayerInstanceFromIndex(int index)
|
Get a script handle of a player using the player index.
Примечание:The 'fake' SourceTV player will always be returned as null.
|
PlayerReadyStatus_ArePlayersOnTeamReady
|
bool PlayerReadyStatus_ArePlayersOnTeamReady(int team)
|
|
PlayerReadyStatus_HaveMinPlayersToEnable
|
bool PlayerReadyStatus_HaveMinPlayersToEnable()
|
|
PlayerReadyStatus_ResetState
|
void PlayerReadyStatus_ResetState()
|
|
PlayersAreOnMatchSummaryStage
|
bool PlayersAreOnMatchSummaryStage()
|
|
PointsMayBeCaptured
|
bool PointsMayBeCaptured()
|
Are points able to be captured? |
PrecacheEntityFromTable
|
bool PrecacheEntityFromTable(table keyvalues)
|
Precache an entity from KeyValues in a table. Internally this function creates the entity, fire DispatchSpawn and removes it instantly.
|
PrecacheModel
|
int PrecacheModel(string filename)
|
Precache a model and return index of the model. |
PrecacheScriptSound
|
bool PrecacheScriptSound(string soundName)
|
Precache a soundscript. |
PrecacheSound
|
bool PrecacheSound(string soundName)
|
Precache a raw sound. |
PrintHelp
|
void PrintHelp()
|
Equivalent to running script_help command.
|
RandomFloat
|
float RandomFloat(float min, float max)
|
Generate a random floating-point number within a range, inclusive. |
RandomInt
|
int RandomInt(int min, int max)
|
Generate a random integer within a range, inclusive. |
RegisterFunctionDocumentation
|
void RegisterFunctionDocumentation(unknown func, string name, string signature, string description)
|
|
RegisterScriptGameEventListener
|
void RegisterScriptGameEventListener(string eventName)
|
Register as a listener for a game event from script. It's what __CollectGameEventCallbacks() uses to register event callbacks to the C++ code.
|
RegisterScriptHookListener
|
void RegisterScriptHookListener(string name)
|
Register as a listener for a script hook from script. |
RetrieveNativeSignature
|
string RetrieveNativeSignature(function func)
|
|
RotateOrientation
|
QAngle RotateOrientation(QAngle, QAngle)
|
Rotate a QAngle by another QAngle. |
RotatePosition
|
Vector RotatePosition(Vector origin, QAngle rotation, Vector input)
|
Rotate the input Vector around an origin.
Баг:This is not calculated correctly and the rotation will always be relative to (0, 0, 0). As a workaround, subtract the origin from the input, call this function and then add the origin back which will perform the expected result. [todo tested in?] |
ScreenFade
|
void ScreenFade(handle player, int red, int green, int blue, int alpha, float fadeTime, float fadeHold, int flags)
|
Start a customisable screenfade. If no player is specified, the fade will apply to all players. |
ScreenShake
|
void ScreenShake(Vector vecCenter, float flAmplitude, float flFrequency, float flDuration, float flRadius, int eCommand, bool bAirShake)
|
Start a customisable screenshake; eCommand( SHAKE_START = 0, SHAKE_STOP = 1 ). |
ScriptHooksEnabled
|
bool ScriptHooksEnabled()
|
Returns whether script hooks are currently enabled. |
SendGlobalGameEvent
|
bool SendGlobalGameEvent(string event_name, handle params)
|
Sends a real game event to everything. Parameters are passed in a squirrel table.
Предупреждение:Certain events that are usually clientside only will not work when fired by this function, with an error complaining that "no listeners are registered for this event". However, defining an empty event listener will make it work.
Предупреждение:Events that upload statistics to Steam servers such as
player_escort_score can take as long as 1 millisecond to execute! This can be prevented by temporarily giving the player the FL_FAKECLIENT flag and reverting it afterwards (however be careful not to revert it on actual bots!).
Example: local is_bot = player.IsFakeClient();
if (!is_bot) player.AddFlag(Constants.FPlayer.FL_FAKECLIENT);
SendGlobalGameEvent("player_escort_score",
{
player = player.entindex(),
points = 1
});
if (!is_bot) player.RemoveFlag(Constants.FPlayer.FL_FAKECLIENT);
|
SendToConsole
|
void SendToConsole(string command)
|
Issues a command to the local client, as if they typed in the command in their console. Does nothing on dedicated servers. |
SendToServerConsole
|
void SendToServerConsole(string command)
|
Issues a command to the server, as if typed in the console.
Примечание:This obeys the behavior of the
sv_allow_point_servercommand convar. By default, this command will do nothing unless the server has this command to set to "always" |
SendToConsoleServer
|
void SendToConsoleServer(string command)
|
Copy of SendToServerConsole with another name for compat. |
SetFakeClientConVarValue
|
void SetFakeClientConVarValue(handle bot, string cvar, string value)
|
Sets a USERINFO client ConVar for a fakeclient.
Совет:This can be used to change the name of a bot by using the
name cvar. |
SetGravityMultiplier
|
void SetGravityMultiplier(float multiplier)
|
|
SetMannVsMachineAlarmStatus
|
void SetMannVsMachineAlarmStatus(bool status)
|
|
SetOvertimeAllowedForCTF
|
void SetOvertimeAllowedForCTF(bool state)
|
|
SetPlayersInHell
|
void SetPlayersInHell(bool state)
|
|
SetSkyboxTexture
|
void SetSkyboxTexture(string texture)
|
Sets the current skybox texture. The path is relative to "materials/skybox/". Only the main name of a skybox texture is needed, for example "sky_gravel_01". |
SetUsingSpells
|
void SetUsingSpells(bool state)
|
|
SpawnEntityFromTable
|
handle SpawnEntityFromTable(string name, handle keyvalues)
|
Spawn entity from KeyValues in table - 'name' is entity name, rest are KeyValues for spawn.
Примечание:Multiple keys of the same name can be specified by appending the key with an incremental #x suffix.
Примечание:
parentname is not resolved and therefore will not work. Instead, use SpawnEntityGroupFromTable for that purpose.Совет:If spawning multiple entities at once, use
SpawnEntityGroupFromTable as it will be more efficient.Example: SpawnEntityFromTable("logic_timer", {
targetname = "cool"
RefireTime = 60
"OnTimer#1" = "entity,Trigger,,0,-1"
"OnTimer#2" = "somethingelse,Disable,,0,-1"
})
Предупреждение:If using commas inside the parameter field of a output key, it will not be parsed correctly as the comma will be treated as delimiter.
To fix this, an special delimiter also supported by the game can be used named 'ESC'. This cannot be typed on a keyboard normally, and must be copied from another source. The easiest way is to download the following text file, and copy + paste the character in a supporting editor such as Notepad++. "OnTrigger#5": "res�RunScriptCode�NetProps.SetPropString(self, `m_iszMvMPopfileName`, `test`)�0�-1" Примечание:If using a complex model, usually custom models, it might cause stutters to the server when spawning it. To work around this issue instead spawn it with
CreateByClassname and set its netprops manually, and don't forget to make sure the model is precached properly too. |
SpawnEntityGroupFromTable
|
bool SpawnEntityGroupFromTable(handle groups)
|
Hierarchically spawn an entity group from a set of spawn tables. This computes a spawn order for entities so that parenting is resolved correctly.
The table for this must take the following format. {
<group> =
{
<classname> =
{
// key - values
}
},
// ...
}
Example usage: SpawnEntityGroupFromTable(
{
a =
{
info_particle_system =
{
origin = GetListenServerHost().GetOrigin(),
parentname = "mytarget",
effect_name = "soldierbuff_blue_soldier",
start_active = true
}
},
b =
{
info_particle_system =
{
origin = GetListenServerHost().GetOrigin(),
parentname = "mytarget",
effect_name = "soldierbuff_red_soldier",
start_active = true
}
},
});
|
StringToFile
|
void StringToFile(string file, string string)
|
Stores a string as a file, located in the game's scriptdata folder.
Примечание:This writes files in text mode, therefore binary files will not be written correctly.
Предупреждение:If writing multi-line strings directly, this may cause issues due to Window's encoding new lines as \r\n, but Mac/Linux encodes as \n. This can be fixed by setting EOL encoding to Unix in your text editor.
|
Time
|
float Time()
|
Get the current server time |
TraceLine
|
float TraceLine(Vector start, Vector end, handle ignore)
|
Return fraction along line that hits world or models |
TraceLineEx
|
bool TraceLineEx(table traceTable)
|
Input Table: start, end, mask (optional), ignore (optional) Output Table: pos, fraction, hit, enthit, allsolid, startpos, endpos, startsolid, plane_normal, plane_dist, surface_name, surface_flags, surface_props Returns false if Предупреждение:
allsolid , enthit and startsolid output parameters may not exist depending on the inputs and results of the trace. Check if they exist first before using.Примечание:Default mask is
MASK_VISIBLE_AND_NPCS , which is the combination of the following; CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_OPAQUE|CONTENTS_MONSTER|CONTENTS_IGNORE_NODRAW_OPAQUE Примечание:By default this will trace against the bounding box of models only. Add
CONTENTS_HITBOX to the mask to instead perform precise hitbox tests.Совет:Traces can only ignore 1 entity at a time. For more flexible filtering, see this library.
Совет:To trace against triggers, you will need to revert the trigger's collision group to
COLLISION_GROUP_NONE , remove FSOLID_NOT_SOLID solid flags and then revert after the trace. |
TraceLinePlayersIncluded
|
float TraceLinePlayersIncluded(Vector, Vector, handle)
|
given 2 points & ent to ignore, return fraction along line that hits world, models, players or npcs |
TraceHull
|
bool TraceHull(table traceTable)
|
Input Table: start, end, hullmin, hullmax, mask (optional), ignore (optional) Output Table: pos, fraction, hit, enthit, allsolid, startpos, endpos, startsolid, plane_normal, plane_dist, surface_name, surface_flags, surface_props Returns false if Примечание:Default mask is
MASK_VISIBLE_AND_NPCS , which is the combination of the following; CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_OPAQUE|CONTENTS_MONSTER|CONTENTS_IGNORE_NODRAW_OPAQUE Предупреждение:
allsolid , enthit and startsolid output parameters may not exist depending on the inputs and results of the trace. Check if they exist first before using.Совет:Traces can only ignore 1 entity at a time. For more flexible filtering, see this library.
Совет:To trace against triggers, you will need to revert the trigger's collision group to
COLLISION_GROUP_NONE , remove FSOLID_NOT_SOLID solid flags and then revert after the trace. |
UniqueString
|
string UniqueString(string input)
|
Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table. |
DoUniqueString
|
string DoUniqueString(string input)
|
Unknown; presumably an internal function called by UniqueString, so call that instead. |
UsePlayerReadyStatusMode
|
bool UsePlayerReadyStatusMode()
|
|
VSquirrel_OnCreateScope
|
table VSquirrel_OnCreateScope(any value, table scope)
|
Creates a new scope with the name of value in the submitted table (includes unique params). |
VSquirrel_OnReleaseScope
|
void VSquirrel_OnReleaseScope(table createdScope)
|
Removes a scope created via VSquirrel_OnCreateScope. |
__CollectEventCallbacks
|
void __CollectEventCallbacks(scope, prefix, globalTableName, regFunc)
|
Overloaded function. Its only used for this: __CollectEventCallbacks(scope, "OnGameEvent_", "GameEventCallbacks", ::RegisterScriptGameEventListener)
|
__CollectGameEventCallbacks
|
void __CollectGameEventCallbacks(table scope)
|
Wrapper that registers callbacks for both OnGameEvent_x and OnScriptEvent_ functions. Done using the __CollectEventCallbacks function.
|
__ReplaceClosures
|
void __ReplaceClosures(script, scope)
|
|
__RunEventCallbacks
|
void __RunEventCallbacks(event, params, prefix, globalTableName, bWarnIfMissing)
|
Call all functions in the callback array for the given game event |
__RunGameEventCallbacks
|
void __RunGameEventCallbacks(event, params)
|
Wrapper for __RunEventCallbacks()
|
__RunScriptHookCallbacks
|
void __RunScriptHookCallbacks(event, param)
|
Вывод и рисование
Функции для вывода сообщений или рисования элементов в мире обычно используются для отладки.
Debug
требуют включённый developer
и игру не на паузе.Они так же не появляются в многопользовательской игре, только на локальном сервере.
Функция | Написание | Описание | |
---|---|---|---|
ClientPrint
|
void ClientPrint(CBasePlayer player, EHudNotify destination, string message)
|
Print a client message. If you pass null instead of a valid player, the message will be sent to all clients. When printing to chat (HUD_PRINTTALK), the color of the text can be changed by inserting this sequence: \x07RRGGBB where RR GG BB is the hexadecimal format of the color. Transparency can be specified by a different sequence: \x08RRGGBBAA , where RR GG BB AA is the hexadecimal format of the color + alpha. All text following this sequence will be colored. Multiple sequences can be used in combination. If using color sequences, there MUST be a color sequence at the beginning of the string, or color codes won't work!.
Предупреждение: Will not accept these escape sequences. As a result, you cannot print colored text with a simple RunScriptCode input.
Обходной приём:See the VScript Examples page for a workaround that replaces a normal character with \x07 at run-timeСовет:Standard chat colors:
| |
DebugDrawBox
|
void DebugDrawBox(Vector origin, vector min, vector max, int r, int g, int b, int alpha, float duration)
|
Draw a debug overlay box. | |
DebugDrawBoxAngles
|
void DebugDrawBoxAngles(Vector origin, Vector min, Vector max, QAngle direction, Vector rgb, int alpha, float duration)
|
Draw a debug oriented box (cent, min, max, angles(p,y,r), vRgb, a, duration). | |
DebugDrawBoxDirection
|
void DebugDrawBoxDirection(Vector center, Vector min, Vector max, Vector forward, Vector rgb, float alpha, float duration)
|
Draw a debug forward box. | |
DebugDrawCircle
|
void DebugDrawCircle(Vector center, Vector rgb, float alpha, float radius, bool ztest, float duration)
|
Draw a debug circle. | |
DebugDrawClear
|
void DebugDrawClear()
|
Try to clear all the debug overlay info. | |
DebugDrawLine
|
void DebugDrawLine(Vector start, Vector end, int red, int green, int blue', bool zTest, float time)
|
Draw a debug overlay line. | |
DebugDrawLine_vCol
|
void DebugDrawLine_vCol(Vector start, vector end, vector rgb, bool ztest, float duration)
|
Draw a debug line using color vec. | |
DebugDrawScreenTextLine
|
void DebugDrawScreenTextLine(float x, float y, int lineOffset, string text, int r, int g, int b, int a, float duration)
|
Draw text with a line offset. | |
DebugDrawText
|
void DebugDrawText(Vector origin, string text, bool useViewCheck, float duration)
|
Draw text on the screen, starting on the position of origin. | |
__DumpScope
|
void __DumpScope(int indentation, table scope)
|
Dumps a scope's contents and expands all tables and arrays; this is what the ent_script_dump command uses.
Совет:You can use this to print tables/arrays.
| |
DumpObject
|
void DumpObject(handle object)
|
Dumps information about a class or instance. | |
Msg
|
void Msg(string message)
|
Prints message to console without any line feed after. | |
printf
|
void printf(string format, args...)
|
Prints message to console with C style formatting. The line feed is not included. | |
printl
|
void printl(string message)
|
Prints message to console with a line feed after. | |
realPrint
|
void realPrint(string message)
|
Identical to print. print seems to be a wrapper for this. | |
Say
|
void Say(CBasePlayer player, string message, bool teamOnly)
|
Calling this will have the specified player send the message to chat, either to teamOnly (true) or to everyone. | |
ShowMessage
|
void ShowMessage(string message)
|
Print a hud message on all clients Баг:Non-functional. [todo tested in?] |
Стандартные библиотеки Squirrel
Стандартные функции Squirrel и стандартные библиотеки.
Функция | Написание | Описание | |
---|---|---|---|
array
|
array(int length, any fill = null)
|
Возвращает новый массив указанной длины, который заполнен значением fill (по умолчанию - null). | |
assert
|
assert(bool exp)
|
Выбрасывает ошибку утверждения, если указанное выражение является false (т.е. величины 0, 0.0, null и false)
| |
callee
|
function callee()
|
Возвращает текущее закрытие. | |
castf2i
|
int castf2i(float value)
|
Интерпретирует указанные байты формата плавающей точки в формат 32-битного целочисленного числа
Предупреждение:Это битовая реинтерпритация, т.е. 1.0 не будет равно 1, а будет равно 1065353216! Используйте
tointeger() для нужного представления. | |
casti2f
|
float casti2f(int value)
|
Интерпретирует указанные байты формата целочисленного числа в формат кодировки плавающей точки
Предупреждение:Это битовая реинтерпритация, т.е 420 не будет равно 420.0, а будет равно 5.88545e^-43! Используйте
tofloat() для нужного представления. | |
collectgarbage
|
int collectgarbage()
|
Запускает сборщик мусора и возвращает число найденых (и удалённых) мусорных циклов. Работает только в сборках сборщика мусора. | |
compilestring
|
any compilestring(string string, string buffername = null)
|
Компилирует строку, состоящую из скрипта squirrel, и возвращает её результат. | |
dummy
|
dummy()
|
||
enabledebuginfo
|
void enabledebuginfo(any enable)
|
Enable/disable the debug line information generation at compile time. enable != null enables . enable == null disables. | |
error
|
void error(string x)
|
Выводит х в качестве стандартного вывода ошибки. | |
getconsttable
|
table getconsttable()
|
Возвращает таблицу констант виртуальной машины. | |
getroottable
|
table getroottable()
|
Возвращает таблицу корней (в иерархии) виртуальной машины. | |
getstackinfos
|
table getstackinfos(int stacklevel)
|
Возвращает информацию стека кадра в указанном уровне стеков (0 - текущая функция, 1 - вызывающий и т.д.). Если уровень стека не существует, то будет возврашён null.
| |
newthread
|
coroutine newthread(function threadfunc)
|
Создаёт совместный объект потока (коорутина) и возвращает его. | |
print
|
print(string message)
|
Выводит этот параметр, но не на новой линии printl()
| |
resurrectunreachable
|
array resurrectunreachable()
|
Runs the garbage collector and returns an array containing all unreachable object found. If no unreachable object is found, null is returned instead. This function is meant to help debugging reference cycles. This function only works on garbage collector builds. | |
setconsttable
|
table setconsttable(table consttable)
|
Sets the const table of the VM which also returns the previous const table. | |
setdebughook
|
void setdebughook(function hook_func)
|
Sets the debug hook. | |
seterrorhandler
|
void seterrorhandler(function func)
|
Sets the runtime error handler . | |
setroottable
|
table setroottable(table roottable)
|
Sets the root table of the VM which also returns the previous root table. | |
suspend
|
void suspend(any ret)
|
Suspends the coroutine that called this function. | |
swap2
|
int swap2(int value)
|
Swaps bytes 1 and 2 of the integer | |
swap4
|
int swap4(int value)
|
Reverse byte order of the four bytes | |
swapfloat
|
float swapfloat(float value)
|
Reverse byte order of the four bytes | |
type
|
type(var)
|
Returns var._typeof(), i.e. the type of the given parameter as a string |
Пузырь
Пузыри хранят блоки бинарных данных. Смотрите официальную документацию для большей информации.
Функция | Написание | Описание |
---|---|---|
blob
|
blob(int initSize = 0)
|
|
eos
|
int eos()
|
|
flush
|
flush()
|
|
len
|
int len()
|
|
readblob
|
blob readblob(int numberOfBytes)
|
|
readn
|
any readn(char dataType)
|
|
resize
|
void resize(int newSize)
|
|
seek
|
int seek(int offset, int offsetBasis)
|
|
swap2
|
void swap2()
|
|
swap4
|
void swap4()
|
|
tell
|
int tell()
|
|
writeblob
|
void writeblob(blob blob)
|
|
writen
|
void writen(num value, char dataType)
|
Математика
Функция | Написание | Описание |
---|---|---|
abs
|
abs(num x)
|
Возвращает модуль от х в качестве целочисленного формата (не как fabs()) |
acos
|
acos(num x)
|
Возвращает косинус в -1'ой степени от х |
asin
|
asin(num x)
|
Возвращает синус в -1'ой степени от х |
atan
|
atan(num x)
|
Возвращает тангенс в -1'ой степени от х |
atan2
|
atan2(num y, num x) (!)
|
Возвращает угол между лучом из точки (0, 0), проведённый через точку (х, у) и положительную ось х, ограниченную (-PI, PI). Смотрите atan2. Правильно указывайте последовательность координат х и у! |
ceil
|
ceil(num x)
|
Возвращает округлённый х в меньшую степень |
cos
|
cos(num x)
|
Возвращает косинус от х |
exp
|
exp(num x)
|
Возвращает экспоненту от х |
fabs
|
fabs(num x)
|
Возвращает модуль от х с плавающей точкой (не как abs()) |
floor
|
floor(num x)
|
Возвращает округлённый х в большую степень |
log
|
log(num x)
|
Возвращает натуральный логарифм от х |
log10
|
log10(num x)
|
Возвращает десятичный логарифм от х |
pow
|
pow(num x, num y)
|
Возвращает х в степени у |
rand
|
rand()
|
Возвращает псевдорандомную цифру с 0 ≤ rand() ≤ RAND_MAX
|
sin
|
sin(num x)
|
Вовзращает синус от х |
sqrt
|
sqrt(num x)
|
Возвращает квадратный корень от х |
srand
|
srand(num seed)
|
Устанавливает семя для последующих псевдорандомных генераций |
tan
|
tan(num x)
|
Возвращает тангенс от х |
Строки
Следующий материал принадлежит в качестве дочерних методов строковых объектов, тоесть они должны вызываться с помощью точки у строки. Например, str.slice(0, 5)
.
Функция | Написание | Описание |
---|---|---|
find
|
int find(string searchString, int startIndex = null)
|
Ищет подстроку в качестве searchString, начиная, или с самого начала, или с указанного индекса startIndex. Если подстрока найдена, возвратит индекс первого совпадения, если не найдена - возвратит null. |
len
|
int len()
|
Возвращает длинну строки, тоесть её число символов. |
slice
|
string slice(int startIndex, int endIndex = null)
|
Создаёт подстроку из данной строки. Копирует символы с startIndex до endIndex. Если endIndex не указан - будет копировать до конца. Если endIndex больше чем длина строки - возникнет ошибка. |
tofloat
|
float tofloat()
|
Возвращает конвертированную строку в формате с плавающей точкой. Строка должна состоять только из цифр, + или -, иначе возникнет ошибка. |
tointeger
|
int tointeger()
|
Возвращает конвертированную строку в целочисленном формате. Строка должна состоять только из цифр, иначе возникнет ошибка. Поддерживается шеснадцатеричный формат (0xFF ). Если шеснадцатеричная строка содержит более чем 10 символов, включая 0x , будет возвращён -1.
|
tolower
|
string tolower()
|
Возвращает новую строку, написанную строчными буквами. |
toupper
|
string toupper()
|
Возвращает новую строку, написанную заглавными буквами. |
Следующие функции являются общими для всех строк. Например, str = format("%d", num)
.
Функция | Написание | Описание |
---|---|---|
endswith
|
bool endswith(string str, string cmp)
|
Возвращает true, если конец строки совпадает со строкой сравнения. |
escape
|
string escape(string str)
|
Возвращает строку с обратными слешами за указанными символами: “ a b t n v f r \ ” ’ 0 xNN
|
format
|
string format(string format, args...)
|
Возвращает форматированную строку. Работает так же, как и стандартные функции в языке С (кроме *, не поддерживается). |
lstrip
|
string lstrip(string str)
|
Убирает пустые места в начале строки |
rstrip
|
string rstrip(string str)
|
Убирает пустые места в конце строки |
split
|
array split(string str, string separator, bool skipempty = false)
|
Возвращает массив разделённой строки, если разделитель встречается в строке. Разделитель не является частью массива. Параметр разделителей - строка, которая определяет символы для разделения.Если skipempty установлено как true, то пустые строки не будут добавляться в массим. |
startswith
|
bool startswith(string str, string cmp)
|
Возвращает true, если начало строки равняется со строкой сравнения. |
strip
|
string strip(string str)
|
Убирает пустые места в начале строки |
Отладка скрипта
Тут функции для взаимодействия с отладчикомFunctions for interacting with the debugger. Некоторые из которых задокументированы тут .
Функция | Написание | Описание |
---|---|---|
BeginScriptDebug
|
void BeginScriptDebug()
|
|
EndScriptDebug
|
void EndScriptDebug()
|
|
ScriptDebugAddTextFilter
|
void ScriptDebugAddTextFilter()
|
|
ScriptDebugAddTrace
|
void ScriptDebugAddTrace()
|
|
ScriptDebugAddWatch
|
void ScriptDebugAddWatch()
|
|
ScriptDebugAddWatches
|
void ScriptDebugAddWatches()
|
|
ScriptDebugAddWatchPattern
|
void ScriptDebugAddWatchPattern()
|
|
ScriptDebugClearTraces
|
void ScriptDebugClearTraces()
|
|
ScriptDebugClearWatches
|
void ScriptDebugClearWatches()
|
|
ScriptDebugDefaultWatchColor
|
void ScriptDebugDefaultWatchColor()
|
|
ScriptDebugDraw
|
void ScriptDebugDraw()
|
|
ScriptDebugDrawWatches
|
void ScriptDebugDrawWatches()
|
|
ScriptDebugDumpKeys
|
void ScriptDebugDumpKeys()
|
|
ScriptDebugHook
|
void ScriptDebugHook()
|
|
ScriptDebugIterateKeys
|
void ScriptDebugIterateKeys()
|
|
ScriptDebugIterateKeysRecursive
|
void ScriptDebugIterateKeysRecursive()
|
|
ScriptDebugRemoveTextFilter
|
void ScriptDebugRemoveTextFilter()
|
|
ScriptDebugRemoveTrace
|
void ScriptDebugRemoveTrace()
|
|
ScriptDebugRemoveWatch
|
void ScriptDebugRemoveWatch()
|
|
ScriptDebugRemoveWatches
|
void ScriptDebugRemoveWatches()
|
|
ScriptDebugRemoveWatchPattern
|
void ScriptDebugRemoveWatchPattern()
|
|
ScriptDebugText
|
void ScriptDebugText()
|
|
ScriptDebugTextDraw
|
void ScriptDebugTextDraw()
|
|
ScriptDebugTextPrint
|
void ScriptDebugTextPrint()
|
|
ScriptDebugTextTrace
|
void ScriptDebugTextTrace()
|
|
ScriptDebugTraceAll
|
void ScriptDebugTraceAll()
|
|
ScriptDebugWatches
|
void ScriptDebugWatches()
|
|
__VScriptServerDebugHook
|
__VScriptServerDebugHook()
|