mirror of
https://github.com/MihailRis/voxelcore.git
synced 2026-11-20 09:29:44 +00:00
docs: explain player entity and velocity damping in ecs.md
Describe what the entity bound to a player is and what entity:get_player() is used for. Document how linear_damping and vdamping affect the body velocity (formula from PhysicsSolver), value ranges, defaults, bool values of set_vdamping and the fixed damping used while the body is grounded. Closes #867
This commit is contained in:
parent
1dd1af1a72
commit
8a3bdc504b
2 changed files with 120 additions and 0 deletions
|
|
@ -35,6 +35,7 @@ entity:set_enabled(name: str, enable: bool)
|
|||
-- Returns id of player the entity is bound, otherwise -1 is returned.
|
||||
-- At components initialization -1 is also returned,
|
||||
-- since the binding occurs after initialization.
|
||||
-- Returns nil if the entity does not exist.
|
||||
entity:get_player() -> int or nil
|
||||
|
||||
-- Checks the 'selectable' property of an entity (raycast opacity)
|
||||
|
|
@ -43,6 +44,22 @@ body:is_selectable() -> bool
|
|||
body:set_selectable(flag: bool)
|
||||
```
|
||||
|
||||
### Player entity
|
||||
|
||||
An entity bound to a player serves as the player's body: the player position
|
||||
is taken from its Transform, and the player hitbox is its Rigidbody. The engine
|
||||
spawns this entity automatically from the definition set by the `player-entity`
|
||||
parameter of `config/defaults.toml` (`base:player` in the base pack) and binds
|
||||
it to the player. `player.get_entity(playerid)` returns the player entity ID.
|
||||
|
||||
`entity:get_player()` lets you tell the player entity apart from other entities
|
||||
and find out which player it belongs to. For example, the dropped item component
|
||||
`base:drop` checks `other:get_player()` when touching another entity: a player
|
||||
picks the item up, while another dropped item gets merged into one stack.
|
||||
|
||||
Use the [on_player_set](#component-events) component event to run code
|
||||
when the binding happens.
|
||||
|
||||
## Custom Components
|
||||
|
||||
A component is defined as a script in `{pack}/scripts/components/{name}.lua`.
|
||||
|
|
@ -118,6 +135,7 @@ body:is_vdamping() -> bool
|
|||
-- Returns the vertical damping multiplier
|
||||
body:get_vdamping() -> number
|
||||
-- Enables/disables vertical damping / sets vertical damping multiplier
|
||||
-- (true is 1.0, false is 0.0)
|
||||
body:set_vdamping(enabled: bool | number)
|
||||
|
||||
-- Checks if the entity is on the ground
|
||||
|
|
@ -152,6 +170,48 @@ body:set_elasticity(elasticity: number)
|
|||
body:get_ground_vel() -> vec3
|
||||
```
|
||||
|
||||
#### Velocity damping
|
||||
|
||||
After the movement is calculated, the body velocity changes every frame
|
||||
as follows (`delta` is the frame duration in seconds):
|
||||
|
||||
```lua
|
||||
-- pseudocode
|
||||
local k = body:is_grounded() and 10.0 or body:get_linear_damping()
|
||||
local ground_vel = body:get_ground_vel()
|
||||
|
||||
vel.x = vel.x + (ground_vel.x - vel.x) * delta * k
|
||||
vel.z = vel.z + (ground_vel.z - vel.z) * delta * k
|
||||
if body:get_vdamping() > 0 then
|
||||
vel.y = vel.y / (1 + delta * k * body:get_vdamping())
|
||||
end
|
||||
```
|
||||
|
||||
**linear_damping** (0.5 by default) is the decay rate of the horizontal
|
||||
velocity relative to the surface the body is on. The value is not limited
|
||||
to the 0..1 range:
|
||||
- 0 - no damping, the body keeps its horizontal velocity in the air;
|
||||
- the greater the value, the faster the damping: the horizontal velocity
|
||||
decreases roughly e^(k*t) times in t seconds. At 0.5 it halves in about
|
||||
1.4 s, at 10 - in about 0.07 s;
|
||||
- at `delta * k = 1` (e.g. k = 60 at 60 FPS) the velocity is cancelled
|
||||
in one frame. Greater values overshoot the surface velocity, and at
|
||||
`delta * k > 2` the velocity starts to grow.
|
||||
|
||||
While the body is on the ground (`body:is_grounded()`), the fixed value 10
|
||||
(surface friction) is used instead of the set one, so `set_linear_damping`
|
||||
only affects movement in the air.
|
||||
|
||||
**vdamping** (1.0 by default) is the vertical velocity damping multiplier
|
||||
relative to `k`. It does not affect horizontal damping:
|
||||
- 0 (or `false`) - the vertical velocity is not damped;
|
||||
- 1 (or `true`) - the vertical velocity is damped as fast as the horizontal one;
|
||||
- values above 1 strengthen vertical damping, values below 1 weaken it.
|
||||
|
||||
Vertical damping limits the falling speed: under constant gravity it tends
|
||||
to about `g * gravity_scale / (k * vdamping)`, where `g` is the world
|
||||
gravity acceleration.
|
||||
|
||||
### Skeleton
|
||||
|
||||
The component is responsible for the entity skeleton. See [rigging](../rigging.md).
|
||||
|
|
|
|||
|
|
@ -35,9 +35,26 @@ entity:set_enabled(name: str, enable: bool)
|
|||
-- Возвращает id игрока, к которому привязана сущность, в ином же случае возвращает -1.
|
||||
-- Во время инициализации компонентов при спавне сущности так же возвращает -1,
|
||||
-- так как привязка происходит после инициализации.
|
||||
-- Возвращает nil, если сущность не существует.
|
||||
entity:get_player() -> int или nil
|
||||
```
|
||||
|
||||
### Сущность игрока
|
||||
|
||||
Сущность, привязанная к игроку, служит его телом: позиция игрока берётся
|
||||
из её Transform, а хитбокс игрока — это её Rigidbody. Движок спавнит такую
|
||||
сущность автоматически по определению из параметра `player-entity` файла
|
||||
`config/defaults.toml` (в паке base — `base:player`) и привязывает её к игроку.
|
||||
ID сущности игрока возвращает `player.get_entity(playerid)`.
|
||||
|
||||
`entity:get_player()` позволяет отличить сущность игрока от прочих сущностей
|
||||
и узнать, какому игроку она принадлежит. Например, компонент выпавшего предмета
|
||||
`base:drop` при касании другой сущности проверяет `other:get_player()`:
|
||||
игрок подбирает предмет, а другой выпавший предмет объединяется с ним в стопку.
|
||||
|
||||
Чтобы выполнить код в момент привязки, используйте событие компонента
|
||||
[on_player_set](#события-компонента).
|
||||
|
||||
## Встроенные компоненты
|
||||
|
||||
### Transform
|
||||
|
|
@ -102,6 +119,7 @@ body:is_vdamping() -> bool
|
|||
-- Возвращает множитель вертикального затухания скорости
|
||||
body:get_vdamping() -> number
|
||||
-- Включает/выключает вертикальное затухание скорости / устанавливает значение множителя
|
||||
-- (true соответствует 1.0, false — 0.0)
|
||||
body:set_vdamping(enabled: bool | number)
|
||||
|
||||
-- Проверяет, находится ли сущность на земле (приземлена)
|
||||
|
|
@ -141,6 +159,48 @@ body:is_selectable() -> bool
|
|||
body:set_selectable(flag: bool)
|
||||
```
|
||||
|
||||
#### Затухание скорости
|
||||
|
||||
После расчёта движения скорость тела за каждый кадр меняется так
|
||||
(`delta` — длительность кадра в секундах):
|
||||
|
||||
```lua
|
||||
-- псевдокод
|
||||
local k = body:is_grounded() and 10.0 or body:get_linear_damping()
|
||||
local ground_vel = body:get_ground_vel()
|
||||
|
||||
vel.x = vel.x + (ground_vel.x - vel.x) * delta * k
|
||||
vel.z = vel.z + (ground_vel.z - vel.z) * delta * k
|
||||
if body:get_vdamping() > 0 then
|
||||
vel.y = vel.y / (1 + delta * k * body:get_vdamping())
|
||||
end
|
||||
```
|
||||
|
||||
**linear_damping** (по умолчанию 0.5) — скорость затухания горизонтальной
|
||||
скорости относительно поверхности, на которой находится тело. Значение не
|
||||
ограничено диапазоном 0..1:
|
||||
- 0 — затухания нет, тело в воздухе сохраняет горизонтальную скорость;
|
||||
- чем больше значение, тем быстрее затухание: горизонтальная скорость
|
||||
уменьшается примерно в e^(k*t) раз за t секунд. При 0.5 она падает вдвое
|
||||
примерно за 1.4 с, при 10 — примерно за 0.07 с;
|
||||
- при `delta * k = 1` (например, k = 60 при 60 FPS) скорость гасится
|
||||
за один кадр. Значения больше этого дают перескок через скорость
|
||||
поверхности, а при `delta * k > 2` скорость начинает расти.
|
||||
|
||||
Пока тело стоит на земле (`body:is_grounded()`), вместо установленного
|
||||
значения используется фиксированное значение 10 (трение о поверхность),
|
||||
поэтому `set_linear_damping` влияет только на движение в воздухе.
|
||||
|
||||
**vdamping** (по умолчанию 1.0) — множитель затухания вертикальной скорости
|
||||
относительно `k`. На горизонтальное затухание не влияет:
|
||||
- 0 (или `false`) — вертикальная скорость не затухает;
|
||||
- 1 (или `true`) — вертикальная скорость затухает так же быстро, как горизонтальная;
|
||||
- значения больше 1 усиливают вертикальное затухание, меньше 1 — ослабляют.
|
||||
|
||||
Вертикальное затухание ограничивает скорость падения: при постоянной
|
||||
гравитации она стремится примерно к `g * gravity_scale / (k * vdamping)`,
|
||||
где `g` — ускорение свободного падения в мире.
|
||||
|
||||
### Skeleton
|
||||
|
||||
Компонент отвечает за скелет сущности. См. [риггинг](../rigging.md).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue