This commit is contained in:
Xertis
2025-09-30 23:45:25 +03:00
181 changed files with 4659 additions and 1546 deletions
+26
View File
@@ -297,3 +297,29 @@ Methods are used to manage the overwriting of properties when extending a block
### `property_name@append`
Adds elements to the end of the list instead of completely overwriting it.
## Tags
Tags allow you to designate general properties of blocks. Names should be formatted as `prefix:tag_name`.
The prefix is optional, but helps avoid unwanted logical collisions. Example:
```json
{
"tags": [
"core:ore",
"base_survival:food",
]
}
```
Block tags can also be added from other packs using the `your_pack:tags.toml` file. Example:
```toml
"prefix:tag_name" = [
"random_pack:some_block",
"another_pack:item",
]
"other_prefix:other_tag_name" = [
# ...
]
``
+5
View File
@@ -30,6 +30,11 @@ If prefix is not specified, '!' level will be used.
Example: '~randutil' - weak dependency 'randutil'.
Dependency version is indicated after '@' symbol and have operators to restrict acceptable versions.
If version is not specified, '\*' (any) version will be used.
Example: 'randutil@>=1.0' - dependency 'randutil' which requires version 1.0 or newer.
Example:
```json
{
+16
View File
@@ -20,6 +20,22 @@ Example:
]
```
You can pass values in ARGS from the entity configuration.
They will be passed both when creating a new entity and when loading a saved one.
The `args` list is used for this:
```json
"components": [
{
"name": "base:drop",
"args": {
"item": "base:stone.item",
"count": 1
}
}
]
```
The components code should be in `scripts/components`.
## Physics
+26
View File
@@ -66,3 +66,29 @@ Property status is displayed in the inventory interface. Display method is defin
- `number` - number
- `relation` - current value to initial value (x/y)
- `vbar` - vertical scale (used by default)
## Tags
Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`.
The prefix is optional, but helps avoid unwanted logical collisions. Example:
```json
{
"tags": [
"core:fuel",
"base_survival:poison",
]
}
```
Tags can also be added to items from other packs using the `your_pack:tags.toml` file. Example
```toml
"prefix:tag_name" = [
"random_pack:item",
"another_pack:some_block",
]
"other_prefix:other_tag_name" = [
# ...
]
```
+2 -2
View File
@@ -1,8 +1,8 @@
# Documentation
Documentation for 0.29 (in-development).
Documentation for 0.30 (in development).
[Documentation for release 0.28](https://github.com/MihailRis/voxelcore/blob/release-0.28/doc/en/main-page.md)
[Documentation for 0.29.](https://github.com/MihailRis/voxelcore/blob/release-0.29/doc/ru/main-page.md)
## Sections
+2
View File
@@ -32,8 +32,10 @@ Subsections:
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [pathfinding](scripting/builtins/libpathfinding.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)
- [random](scripting/builtins/librandom.md)
- [rules](scripting/builtins/librules.md)
- [time](scripting/builtins/libtime.md)
- [utf8](scripting/builtins/libutf8.md)
+5 -2
View File
@@ -25,9 +25,12 @@ Waits for the specified time in seconds, performing the main engine loop.
app.sleep_until(
-- function that checks the condition for ending the wait
predicate: function() -> bool,
-- the maximum number of engine loop ticks after which
-- maximum number of engine loop ticks after which
-- a "max ticks exceed" exception will be thrown
[optional] max_ticks = 1e9
[optional] max_ticks = 1e9,
-- maximum wait time in seconds.
-- (works with system time, including test mode)
[optional] timeout = 1e9
)
```
+6
View File
@@ -8,4 +8,10 @@ base64.encode(bytes: table|ByteArray) -> str
-- Decode base64 string to ByteArray or lua table if second argument is set to true
base64.decode(base64string: str, [optional]usetable: bool=false) -> table|ByteArray
-- Encode bytes to urlsafe-base64 string ('-', '_' instead of '+', '/')
base64.encode_urlsafe(bytes: table|ByteArray) -> str
-- Decodes urlsafe-base64 string to a ByteArray or a table of numbers if the second argument is set to true
base64.decode_urlsafe(base64string: str, [optional]usetable: bool=false) -> table|ByteArray
```
+3
View File
@@ -68,6 +68,9 @@ block.get_variant(x: int, y: int, z: int) -> int
-- Sets the block variant by index
block.set_variant(x: int, y: int, z: int, index: int) -> int
-- Checks if an block has specified tag
block.has_tag(id: int, tag: str) -> bool
```
## Rotation
+3
View File
@@ -33,4 +33,7 @@ item.emission(itemid: int) -> str
-- Returns the value of the `uses` property
item.uses(itemid: int) -> int
-- Checks if an item has specified tag
item.has_tag(itemid: int, tag: str) -> bool
```
+26 -5
View File
@@ -6,9 +6,15 @@ A library for working with the network.
```lua
-- Performs a GET request to the specified URL.
-- After receiving the response, passes the text to the callback function.
-- In case of an error, the HTTP response code will be passed to onfailure.
network.get(url: str, callback: function(str), [optional] onfailure: function(int))
network.get(
url: str,
-- Function to call when response is received
callback: function(str),
-- Error handler
[optional] onfailure: function(int, str),
-- List of additional request headers
[optional] headers: table<str>
)
-- Example:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
@@ -16,13 +22,28 @@ network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/lat
end)
-- A variant for binary files, with a byte array instead of a string in the response.
network.get_binary(url: str, callback: function(table|ByteArray), [optional] onfailure: function(int))
network.get_binary(
url: str,
callback: function(ByteArray),
[optional] onfailure: function(int, str),
[optional] headers: table<str>
)
-- Performs a POST request to the specified URL.
-- Currently, only `Content-Type: application/json` is supported
-- After receiving the response, passes the text to the callback function.
-- In case of an error, the HTTP response code will be passed to onfailure.
network.post(url: str, data: table, callback: function(str), [optional] onfailure: function(int))
network.post(
url: str,
-- Request body as a table (will be converted to JSON) or string
body: table|str,
-- Function called when response is received
callback: function(str),
-- Error handler
[optional] onfailure: function(int, str),
-- List of additional request headers
[optional] headers: table<str>
)
```
## TCP Connections
@@ -0,0 +1,66 @@
# *pathfinding* library
The *pathfinding* library provides functions for working with the pathfinding system in the game world. It allows you to create and manage agents finding routes between points in the world.
When used in entity logic, the `core:pathfinding` component should be used.
## `core:pathfinding` component
```lua
local pf = entity:get_component("core:pathfinding")
--- ...
local x = ...
local y = ...
local z = ...
--- Set the target for the agent
pf.set_target({x, y, z})
--- Get the current target of the agent
local target = pf.get_target() --> vec3 or nil
--- ...
--- Get the current route of the agent
local route = pf.get_route() --> table<vec3> or nil
--- ...
```
## Library functions
```lua
--- Create a new agent. Returns the ID of the created agent
local agent = pathfinding.create_agent() --> int
--- Delete an agent by ID. Returns true if the agent existed, otherwise false
pathfinding.remove_agent(agent: int) --> bool
--- Set the agent state (enabled/disabled)
pathfinding.set_enabled(agent: int, enabled: bool)
--- Check the agent state. Returns true if the agent is enabled, otherwise false
pathfinding.is_enabled(agent: int) --> bool
--- Create a route based on the given points. Returns an array of route points
pathfinding.make_route(start: vec3, target: vec3) --> table<vec3>
--- Asynchronously create a route based on the given points.
--- This function allows to perform pathfinding in the background without blocking the main thread of execution
pathfinding.make_route_async(agent: int, start: vec3, target: vec3)
--- Get the route that the agent has already found. Used to get the route after an asynchronous search.
--- If the search has not yet completed, returns nil. If the route is not found, returns an empty table.
pathfinding.pull_route(agent: int) --> table<vec3> or nil
--- Set the maximum number of visited blocks for the agent. Used to limit the amount of work of the pathfinding algorithm.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Adding an avoided blocks tag
pathfinding.avoid_tag(
agent: int,
-- tag for avoided blocks
tag: string, [optional],
-- cost of crossing a block
cost: int = 10
)
```
+7
View File
@@ -89,6 +89,13 @@ player.set_loading_chunks(playerid: int, bool)
Getter and setter of the property that determines whether the player is loading chunks.
```lua
player.get_interaction_distance(playerid: int) -> float
player.set_interaction_distance(playerid: int, distance: float)
```
Getter and setter of the property for max interaction distance.
``` lua
player.set_spawnpoint(playerid: int, x: number, y: number, z: number)
player.get_spawnpoint(playerid: int) -> number, number, number
+38
View File
@@ -0,0 +1,38 @@
# *random* library
A library of functions for generating random numbers.
## Non-deterministic numbers
```lua
-- Generates a random number in the range [0..1)
random.random() --> number
-- Generates a random integer in the range [0..n]
random.random(n) --> number
-- Generates a random integer in the range [a..b]
random.random(a, b) --> number
-- Generates a random byte array of length n
random.bytes(n: number) -> Bytearray
-- Generates a UUID version 4
random.uuid() -> str
```
## Pseudorandom numbers
The library provides the Random class - a generator with its own isolated state.
```lua
local rng = random.Random()
-- Used similarly to math.random
local a = rng:random() --> [0..1)
local b = rng:random(10) --> [0..10]
local c = rng:random(5, 20) --> [5..20]
-- Sets the generator state to generate a reproducible sequence of random numbers
rng:seed(42)
```
+31
View File
@@ -100,6 +100,13 @@ vecn.length(a: vector)
```
#### Distance - *vecn.distance(...)*
```lua
-- returns the distance between two vectors
vecn.distance(a: vector, b: vector)
```
#### Absolute value - *vecn.abs(...)*
```lua
@@ -136,6 +143,16 @@ vecn.pow(v: vector, exponent: number, dst: vector)
vecn.dot(a: vector, b: vector)
```
#### Mixing - *vecn.mix(...)*
```lua
-- returns vector a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number)
-- writes to dst vector a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number, dst: vector)
```
#### Convert to string - *vecn.tostring(...)*
> [!WARNING]
> Returns only if the content is a vector
@@ -160,6 +177,12 @@ vec2.angle(v: vec2)
-- returns the direction angle of the vector {x, y} in degrees [0, 360]
vec2.angle(x: number, y: number)
-- returns the vector rotated by an angle in degrees counterclockwise
vec2.rotate(v: vec2, angle: number) -> vec2
-- writes the vector rotated by an angle in degrees counterclockwise to dst
vec2.rotate(v: vec2, angle: number, dst: vec2) -> vec2
```
@@ -188,6 +211,10 @@ print("mul: " .. vec3.tostring(result_mul)) -- {10, 40, 80}
local result_mul_scal = vec3.mul(v1_3d, scal)
print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12}
-- calculating distance between vectors
local result_distance = vec3.distance(v1_3d, v2_3d)
print("distance: " .. result_distance) -- 43
-- vector normalization
local result_norm = vec3.normalize(v1_3d)
print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667}
@@ -211,3 +238,7 @@ print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4}
-- scalar product of vectors
local result_dot = vec3.dot(v1_3d, v2_3d)
print("dot: " ..result_dot) -- 250
-- mixing vectors
local result_mix = vec3.mix(v1_3d, v2_3d, 0.25)
print("mix: " .. vec3.tostring(result_mix)) -- {3.25, 6.5, 11.5}
+13 -3
View File
@@ -26,6 +26,8 @@ entity:get_uid() -> int
entity:get_component(name: str) -> component or nil
-- Checks for the presence of a component by name
entity:has_component(name: str) -> bool
-- Retrieves a component by name. Throws an exception if it does not exist
entity:require_component(name: str) -> component
-- Enables/disables the component
entity:set_enabled(name: str, enable: bool)
@@ -93,10 +95,12 @@ body:get_linear_damping() -> number
-- Sets the linear velocity attenuation multiplier
body:set_linear_damping(value: number)
-- Checks if vertical velocity attenuation is enabled
-- Checks if vertical damping is enabled
body:is_vdamping() -> bool
-- Enables/disables vertical velocity attenuation
body:set_vdamping(enabled: bool)
-- Returns the vertical damping multiplier
body:get_vdamping() -> number
-- Enables/disables vertical damping / sets vertical damping multiplier
body:set_vdamping(enabled: bool | number)
-- Checks if the entity is on the ground
body:is_grounded() -> bool
@@ -188,6 +192,12 @@ function on_update(tps: int)
Called every entities tick (currently 20 times per second).
```lua
function on_physics_update(delta: number)
```
Called after each physics step
```lua
function on_render(delta: number)
```
+7
View File
@@ -46,6 +46,13 @@ function on_blocks_tick(tps: int)
Called tps (20) times per second. Use 1/tps instead of `time.delta()`.
```lua
function on_block_tick(x, y, z, tps: number)
```
Called tps (20 / tick-interval) times per second for a block.
Use 1/tps instead of `time.delta()`.
```lua
function on_player_tick(playerid: int, tps: int)
```
+26
View File
@@ -306,3 +306,29 @@
### `имя_свойства@append`
Добавляет элементы в конец списка, вместо его полной перезаписи.
## Теги - *tags*
Теги позволяют обозначать обобщённые свойства блоков. Названия следует формировать как `префикс:имя_тега`.
Префикс не является обязательным, но позволяет избегать нежелательных логических коллизий. Пример:
```json
{
"tags": [
"core:ore",
"base_survival:food",
]
}
```
Теги блокам можно добавлять и из других паков, с помощью файла `ваш_пак:tags.toml`. Пример
```toml
"префикс:имя_тега" = [
"рандомный_пак:какой_то_блок",
"ещё_один_пак:предмет",
]
"другой_префикс:другое_имя_тега" = [
# ...
]
```
+5
View File
@@ -32,6 +32,11 @@
Пример: '~randutil' - слабая зависимость 'randutil'.
Версии зависимостей указываются после '@' и имеют операторы для ограничения допустимых версий.
Отсутствие версии зависимости интерпретируется как '\*', т.е. любая версия.
Пример: 'randutil@>=1.0' - зависимость 'randutil' версии 1.0 и старше.
Пример:
```json
{
+16
View File
@@ -20,6 +20,22 @@
]
```
Из конфигурации сущности можно передавать значения в ARGS.
Они будут передаваться как при создании новой сущности, так и при загрузке сохранённой.
Для этого используется список `args`:
```json
"components": [
{
"name": "base:drop",
"args": {
"item": "base:stone.item",
"count": 1
}
}
]
```
Код компонентов должен находиться в `scripts/components`.
## Физика
+27
View File
@@ -65,3 +65,30 @@
- `number` - число
- `relation` - отношение текущего значения к изначальному (x/y)
- `vbar` - вертикальная шкала (используется по-умолчанию)
## Теги - *tags*
Теги позволяют обозначать обобщённые свойства предметов. Названия следует формировать как `префикс:имя_тега`.
Префикс не является обязательным, но позволяет избегать нежелательных логических коллизий. Пример:
```json
{
"tags": [
"core:fuel",
"base_survival:poison",
]
}
```
Теги предметам можно добавлять и из других паков, с помощью файла `ваш_пак:tags.toml`. Пример
```toml
"префикс:имя_тега" = [
"рандомный_пак:предмет",
"ещё_один_пак:какой_то_блок",
]
"другой_префикс:другое_имя_тега" = [
# ...
]
```
+2 -2
View File
@@ -1,8 +1,8 @@
# Документация
Документация версии 0.29 (в разработке).
Документация версии 0.30 (в разработке).
[Документация версии 0.28](https://github.com/MihailRis/voxelcore/blob/release-0.28/doc/ru/main-page.md)
[Документация 0.29.](https://github.com/MihailRis/voxelcore/blob/release-0.29/doc/ru/main-page.md)
## Разделы
+2
View File
@@ -32,8 +32,10 @@
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [pathfinding](scripting/builtins/libpathfinding.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)
- [random](scripting/builtins/librandom.md)
- [rules](scripting/builtins/librules.md)
- [time](scripting/builtins/libtime.md)
- [utf8](scripting/builtins/libutf8.md)
+4 -1
View File
@@ -27,7 +27,10 @@ app.sleep_until(
predicate: function() -> bool,
-- максимальное количество тактов цикла движка, после истечения которых
-- будет брошено исключение "max ticks exceed"
[опционально] max_ticks = 1e9
[опционально] max_ticks = 1e9,
-- максимальное длительность ожидания в секундах.
-- (работает с системным временем, включая test-режим)
[опционально] timeout = 1e9
)
```
+6
View File
@@ -8,4 +8,10 @@ base64.encode(bytes: table|ByteArray) -> str
-- Декодирует base64 строку в ByteArray или таблицу чисел, если второй аргумент установлен на true
base64.decode(base64string: str, [опционально]usetable: bool=false) -> table|ByteArray
-- Кодирует массив байт в urlsafe-base64 строку ('-', '_' вместо '+', '/')
base64.encode_urlsafe(bytes: table|ByteArray) -> str
-- Декодирует urlsafe-base64 строку в ByteArray или таблицу чисел, если второй аргумент установлен на true
base64.decode_urlsafe(base64string: str, [опционально]usetable: bool=false) -> table|ByteArray
```
+3
View File
@@ -67,6 +67,9 @@ block.get_variant(x: int, y: int, z: int) -> int
-- Устанавливает вариант блока по индексу
block.set_variant(x: int, y: int, z: int, index: int) -> int
-- Проверяет наличие тега у блока
block.has_tag(id: int, tag: str) -> bool
```
### Raycast
+3
View File
@@ -33,6 +33,9 @@ item.emission(itemid: int) -> str
-- Возвращает значение свойства `uses`
item.uses(itemid: int) -> int
-- Проверяет наличие тега у предмета
item.has_tag(itemid: int, tag: str) -> bool
```
+26 -5
View File
@@ -6,9 +6,15 @@
```lua
-- Выполняет GET запрос к указанному URL.
-- После получения ответа, передаёт текст в функцию callback.
-- В случае ошибки в onfailure будет передан HTTP-код ответа.
network.get(url: str, callback: function(str), [опционально] onfailure: function(int))
network.get(
url: str,
-- Функция, вызываемая при получении ответа
callback: function(str),
-- Обработчик ошибок
[опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса
[опционально] headers: table<str>
)
-- Пример:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
@@ -16,13 +22,28 @@ network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/lat
end)
-- Вариант для двоичных файлов, с массивом байт вместо строки в ответе.
network.get_binary(url: str, callback: function(table|ByteArray), [опционально] onfailure: function(int))
network.get_binary(
url: str,
callback: function(ByteArray),
[опционально] onfailure: function(int, Bytearray),
[опционально] headers: table<str>
)
-- Выполняет POST запрос к указанному URL.
-- На данный момент реализована поддержка только `Content-Type: application/json`
-- После получения ответа, передаёт текст в функцию callback.
-- В случае ошибки в onfailure будет передан HTTP-код ответа.
network.post(url: str, data: table, callback: function(str), [опционально] onfailure: function(int))
network.post(
url: str,
-- Тело запроса в виде таблицы, конвертируемой в JSON или строки
body: table|str,
-- Функция, вызываемая при получении ответа
callback: function(str),
-- Обработчик ошибок
[опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса
[опционально] headers: table<str>
)
```
## TCP-Соединения
@@ -0,0 +1,66 @@
# Библиотека *pathfinding*
Библиотека *pathfinding* предоставляет функции для работы с системой поиска пути в игровом мире. Она позволяет создавать и управлять агентами, которые могут находить маршруты между точками в мире.
При использовании в логике сущностей следует использовать компонент `core:pathfinding`.
## Компонент `core:pathfinding`
```lua
local pf = entity:get_component("core:pathfinding")
--- ...
local x = ...
local y = ...
local z = ...
--- Установка цели для агента
pf.set_target({x, y, z})
--- Получение текущей цели агента
local target = pf.get_target() --> vec3 или nil
--- ...
--- Получение текущего маршрута агента
local route = pf.get_route() --> table<vec3> или nil
--- ...
```
## Функции библиотеки
```lua
--- Создание нового агента. Возвращает идентификатор созданного агента
local agent = pathfinding.create_agent() --> int
--- Удаление агента по идентификатору. Возвращает true, если агент существовал, иначе false
pathfinding.remove_agent(agent: int) --> bool
--- Установка состояния агента (включен/выключен)
pathfinding.set_enabled(agent: int, enabled: bool)
--- Проверка состояния агента. Возвращает true, если агент включен, иначе false
pathfinding.is_enabled(agent: int) --> bool
--- Создание маршрута на основе заданных точек. Возвращает массив точек маршрута
pathfinding.make_route(start: vec3, target: vec3) --> table<vec3>
--- Асинхронное создание маршрута на основе заданных точек.
--- Функция позволяет выполнять поиск пути в фоновом режиме, не блокируя основной поток выполнения
pathfinding.make_route_async(agent: int, start: vec3, target: vec3)
--- Получение маршрута, который агент уже нашел. Используется для получения маршрута после асинхронного поиска.
--- Если поиск ещё не завершён, возвращает nil. Если маршрут не найден, возвращает пустую таблицу.
pathfinding.pull_route(agent: int) --> table<vec3> или nil
--- Установка максимального количества посещенных блоков для агента. Используется для ограничения объема работы алгоритма поиска пути.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Добавление тега избегаемых блоков
pathfinding.avoid_tag(
agent: int,
-- тег избегаемых блоков
tag: string, [опционально],
-- стоимость пересечения блока
cost: int = 10
)
```
+7
View File
@@ -89,6 +89,13 @@ player.set_loading_chunks(playerid: int, bool)
Геттер и сеттер свойства, определяющего, прогружает ли игрок чанки вокруг.
```lua
player.get_interaction_distance(playerid: int) -> float
player.set_interaction_distance(playerid: int, distance: float)
```
Геттер и сеттер свойства, определяющего максимальную дистанцию взаимодействия.
```lua
player.set_spawnpoint(playerid: int, x: number, y: number, z: number)
player.get_spawnpoint(playerid: int) -> number, number, number
+38
View File
@@ -0,0 +1,38 @@
# Библиотека *random*
Библиотека функций для генерации случайный чисел.
## Недетерминированные числа
```lua
-- Генерирует случайное число в диапазоне [0..1)
random.random() --> number
-- Генерирует случайное целое число в диапазоне [0..n]
random.random(n) --> number
-- Генерирует случайное целое число в диапазоне [a..b]
random.random(a, b) --> number
-- Генерирует случайный массив байт длиной n
random.bytes(n: number) -> Bytearray
-- Генерирует UUID версии 4
random.uuid() -> str
```
## Псевдослучайные числа
Библиотека предоставляет класс Random - генератор с собственным изолированным состоянием.
```lua
local rng = random.Random()
-- Используется аналогично math.random
local a = rng:random() --> [0..1)
local b = rng:random(10) --> [0..10]
local c = rng:random(5, 20) --> [5..20]
-- Устанавливает состояние генератора для генерации воспроизводимой последовательности случайных чисел
rng:seed(42)
```
+32
View File
@@ -100,6 +100,13 @@ vecn.length(a: vector)
```
#### Дистанция - *vecn.distance(...)*
```lua
-- возвращает расстояние между двумя векторами
vecn.distance(a: vector, b: vector)
```
#### Абсолютное значение - *vecn.abs(...)*
```lua
@@ -136,6 +143,16 @@ vecn.pow(v: vector, exponent: number, dst: vector)
vecn.dot(a: vector, b: vector)
```
#### Смешивание - *vecn.mix(...)*
```lua
-- возвращает вектор a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number)
-- записывает в dst вектор a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number, dst: vector)
```
#### Перевод в строку - *vecn.tostring(...)*
> [!WARNING]
> Возвращает только тогда, когда содержимым является вектор
@@ -160,6 +177,12 @@ vec2.angle(v: vec2)
-- возвращает угол направления вектора {x, y} в градусах [0, 360]
vec2.angle(x: number, y: number)
-- возвращает повернутый вектор на угол в градусах против часовой стрелки
vec2.rotate(v: vec2, angle: number) -> vec2
-- записывает повернутый вектор на угол в градусах против часовой стрелки в dst
vec2.rotate(v: vec2, angle: number, dst: vec2) -> vec2
```
@@ -192,6 +215,10 @@ print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12}
local result_norm = vec3.normalize(v1_3d)
print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667}
-- дистанция между векторами
local result_distance = vec3.distance(v1_3d, v2_3d)
print("distance: " .. result_distance) -- 43
-- длина вектора
local result_len = vec3.length(v1_3d)
print("len: " .. result_len) -- 3
@@ -211,4 +238,9 @@ print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4}
-- скалярное произведение векторов
local result_dot = vec3.dot(v1_3d, v2_3d)
print("dot: " .. result_dot) -- 250
-- смешивание векторов
local result_mix = vec3.mix(v1_3d, v2_3d, 0.25)
print("mix: " .. vec3.tostring(result_mix)) -- {3.25, 6.5, 11.5}
```
+12 -2
View File
@@ -26,6 +26,8 @@ entity:get_uid() -> int
entity:get_component(name: str) -> компонент или nil
-- Проверяет наличие компонента по имени
entity:has_component(name: str) -> bool
-- Запрашивает компонент по имени. Бросает исключение при отсутствии
entity:require_component(name: str) -> компонент
-- Включает/выключает компонент по имени
entity:set_enabled(name: str, enable: bool)
@@ -95,8 +97,10 @@ body:set_linear_damping(value: number)
-- Проверяет, включено ли вертикальное затухание скорости
body:is_vdamping() -> bool
-- Включает/выключает вертикальное затухание скорости
body:set_vdamping(enabled: bool)
-- Возвращает множитель вертикального затухания скорости
body:get_vdamping() -> number
-- Включает/выключает вертикальное затухание скорости / устанавливает значение множителя
body:set_vdamping(enabled: bool | number)
-- Проверяет, находится ли сущность на земле (приземлена)
body:is_grounded() -> bool
@@ -188,6 +192,12 @@ function on_update(tps: int)
Вызывается каждый такт сущностей (на данный момент - 20 раз в секунду).
```lua
function on_physics_update(delta: number)
```
Вызывается после каждого шага физики
```lua
function on_render(delta: number)
```
+7
View File
@@ -46,6 +46,13 @@ function on_blocks_tick(tps: int)
Вызывается tps (20) раз в секунду. Используйте 1/tps вместо `time.delta()`.
```lua
function on_block_tick(x, y, z, tps: number)
```
Вызывается tps (20 / tick-interval) раз в секунду для конкретного блока.
Используйте 1/tps вместо `time.delta()`.
```lua
function on_player_tick(playerid: int, tps: int)
```