Entity object

The Entity object allows you to access the properties of your entities. Entity objects are created by loading an entity definition file using the Game.LoadEntity or Scene.LoadEntity methods. Entities which are part of the scene layout can be queried by using the Scene.GetNode method.


Методы

Actions
SetSprite Sets entity's default sprite.
SetTalkSprite Sets entity's talk sprite.
AddTalkSprite Adds entity's talk sprite.
RemoveTalkSprite Removes a sprite from the list of talk sprites.
GetSprite Queries a default sprite of this entity.
GetSpriteObject Queries a default sprite of this entity.
CreateRegion Creates a region for this entity.
DeleteRegion Removes a region from this entity.
Video playback
PlayTheora Plays a video in Theora format
StopTheora Stops the Theora video playback
IsTheoraPlaying Queries whether the entity is currently playing a Theora video
PauseTheora Pauses the Theora video playback
ResumeTheora Resumes a paused Theora video playback
IsTheoraPaused Queries whether the entity is currently playing a Theora video and the playback is paused
Предметы инвентаря
TakeItem Добавляет предмет в инвентарь.
DropItem Удаляет предмет из инвентаря.
GetItem Возвращает ссылку на предмет инвентаря.
HasItem Выясняет, есть ли в инвентаре объекта (персонажа) указанный предмет.
Miscelaneous functions
Reset Cancels the action the object was currently performing (like talking, walking etc.).
IsTalking Queries whether the object is currently talking.
StopTalking Cancels object's talking.
Talk Makes the object talk.
StickToRegion Forces this actor/entity to act like it's inside a given region
SetFont Sets font of this object.
GetFont Gets a font assigned to this object.
Particle functions
CreateParticleEmitter Initializes the particle emitter attached to this object.
DeleteParticleEmitter Deletes the particle emitter attached to this object.
PlayAnim Plays an animation.
ForceTalkAnim Force a special animation to be used for a subsequent Talk call.
AddAttachment Adds an attached entity to this object.
RemoveAttachment Removes an attached entity from this object.
GetAttachment Gets a reference to an attached entity object.
SkipTo Перемещает объект в указанную точку.
Функции управления курсором
SetCursor Устанавливает стандартный курсор.
GetCursor Возвращает имя файла спрайта курсора или null, если курсор не задан
GetCursorObject Возвращает ссылку на спрайт курсора (объект) или null, если курсор не задан
RemoveCursor Удаляет стандартный курсор.
HasCursor Выясняет, задан ли стандартный курсор для объекта.
Функции для работы со сценариями
AttachScript Выполняет файл сценария и прикрепляет его к объекту.
DetachScript Выгружает из памяти файл сценария и удаляет его связку с объектом.
IsScriptRunning Выясняет, прикреплён ли указанный файл сценария к объекту.
CanHandleMethod Выясняет, поддерживает ли объект метод с указанным именем.
PlaySound Воспроизводит звук. Если имя файла не указано, воспроизводится прикреплённый на настоящий момент звук (если есть).
PlaySoundEvent Воспроизводит звук и генерирует событие, когда воспроизведение закончится. Если имя файла не указано, воспроизводится прикреплённый на настоящий момент звук (если есть).
StopSound Останавливает воспроизведение звука (если есть).
PauseSound Ставит на паузу воспроизведение звука.
ResumeSound Продолжает воспроизведение после паузы.
IsSoundPlaying Выясняет, воспроизводится ли в настоящий момент звуковой файл.
SetSoundPosition Задаёт текущую позицию для воспроизведения в звуковом файле.
GetSoundPosition Возвращает текущую позицию для воспроизведения в звуковом файле
SetSoundVolume Устанавливает громкость звука.
GetSoundVolume Возвращает значение уровня громкости звука.
LoadSound Инициализирует звук из файла, подготавливая его к воспроизведению.
Звуковые эффекты
SoundFXNone Удаляет любой звуковой эффект, прикреплённый к объекту.
SoundFXEcho Задаёт эффект эха для любого звука, привязанного к объекту.
SoundFXReverb Задаёт эффект реверберации для любого звука, привязанного к объекту.
Обработка событий
ApplyEvent Вызывает указанное событие для объекта.
CanHandleEvent Выясняет, имеет ли объект обработчик для указанного события.

Атрибуты

Type (только для чтения) Returns always "entity"
Subtype (только для чтения) Returns either "normal" or "sound" depending on entity type
Item Specifies a name of an inventory item which controls the activity of this entity
SaveState Specifies if the scene entity remembers its state after the player leaves the scene
WalkToX The default postition the actor should walk to using the GoToObject method (X)
WalkToY The default postition the actor should walk to using the GoToObject method (Y)
WalkToDirection The default direction the actor turn to after walking to this entity using the GoToObject method.
Region (только для чтения) Returns a reference to the region object assigned to this entity, or null if no region is assigned.
Active Specifies whether the object is visible on screen
IgnoreItems Specifies whether the object appears to be non-interactive when an inventory item is used on it
SubtitlesPosRelative Specifies whether the SubtitlesPosX and SubtitlesPosY attributes are relative to default position, or absolute screen coordinates
SubtitlesPosX The X position of speech subtitles (either relative to speaker's position or absolute screen coordinates)
SubtitlesPosY The Y position of speech subtitles (either relative to speaker's position or absolute screen coordinates)
SubtitlesWidth Width of speech subtitles. Set to zero to restore the default behavior.
SubtitlesPosXCenter Specifies if the SubtitlesPosX attribute affects the center of the subtitle or its left side.
ParticleEmitter (только для чтения) Returns the reference to the particle emitter object attached to this object, or null if the emitter haven't been initialized yet
NumAttachments (только для чтения) Returns the number of entities attached to this object.
Name Внутреннее имя объекта.
Caption Заголовок объекта.
AccCaption Специальный заголовок объекта, используемый специальными фукциями движка для людей с ослабленным зрением.
X Координата X объекта.
Y Координата Y объекта.
Height (только для чтения) Возвращает текущую высоту объекта (учитывает масштаб персонажей).
Filename (только для чтения) Возвращает имя файла объекта.
Ready (только для чтения) Возвращает true, если объект в настоящий момент не совершает никакого действия.
Interactive Указывает, должен ли объект реагировать на действия пользователя (быть интерактивным).
SoundPanning Указывает, должен ли звук, воспроизводимый данным объектом, панорамироваться в зависимости от его позиции на экране.
NonIntMouseEvents Указывает, должен ли объект реагировать на события MouseEntry и MouseLeave, даже в том случае, если игра работает в неинтерактивном режиме.
Movable Specifies whether the object can be moved by its sprites (in case the sprite frames have a "move" property set).
Scalable Specifies whether the object is affected by scene's scaling levels.
Rotatable Specifies whether the object is affected by scene's rotation levels.
Colorable Specifies whether the object is affected by scene's color regions.
AlphaColor Specifies an RGBA color of this object (overrides scene coloring); set to 0 to reset default behavior.
BlendMode Specifies how the object's image is blended with the background colors; 0...normal mode, 1...additive blending, 2...subtractive blending
Scale Specifies a scale of this object (overrides scene scaling); set to null to reset default behavior.
ScaleX Specifies horizontal scale of this object; set to null to reset default behavior.
ScaleY Specifies vertical scale of this object; set to null to reset default behavior.
RelativeScale Specifies a scale amount to be added to the default scene scale.
Rotate Specifies rotation of this object (in degrees); overrides scene rotation; set to null to reset default behavior; not available in compatibility mode
RelativeRotate Specifies a rotation amount to be added to the default scene rotation.

Низкоуровневые события

MouseEntry The mouse pointer has been just moved over the object.
MouseLeave The mouse pointer has been just moved away from the object.

SetSprite(Filename)

Sets entity's default sprite.

Параметры

Filename
The filename of the sprite file to be used as a default sprite.

Возвращаемое значение

If the method succeeds, the return value is true.


SetTalkSprite(Filename, Extended)

Sets entity's talk sprite.

Параметры

Filename
The filename of the sprite file to be used as a talk sprite.
Extended
Should this sprite be used for explicit talk stances only (optional, default=false).

Возвращаемое значение

If the method succeeds, the return value is true.


AddTalkSprite(Filename, Extended)

Adds entity's talk sprite.

Параметры

Filename
The filename of the sprite file to be added to the list of talk sprites.
Extended
Should this sprite be used for explicit talk stances only (optional, default=false).

Возвращаемое значение

If the method succeeds, the return value is true.


RemoveTalkSprite(Filename)

Removes a sprite from the list of talk sprites.

Параметры

Filename
The filename of the sprite file to be removed.

Возвращаемое значение

If the method succeeds, the return value is true.


GetSprite()

Queries a default sprite of this entity.

Возвращаемое значение

Returns filename of the currently assigned sprite.


GetSpriteObject()

Queries a default sprite of this entity.

Возвращаемое значение

Returns a reference to the currently assigned sprite object.


CreateRegion()

Creates a region for this entity.

Возвращаемое значение

Returns the reference to the region object or null if the creation failed.

Примечания

If the entity already has a region assigned, it's NOT recreated and this method returns the original region.


DeleteRegion()

Removes a region from this entity.

Возвращаемое значение

Returns true if the method succeeded.


PlayTheora(Filename, Looping, AlphaImage)

Plays a video in Theora format

Параметры

Filename
The Ogg Theora file to be played
Looping
Specifies whether the video should loop (optional, default=false)
AlphaImage
Specifies the image to be used for an alpha channel underlying the video playback (optional)

StopTheora()

Stops the Theora video playback


IsTheoraPlaying()

Queries whether the entity is currently playing a Theora video

Возвращаемое значение

Returns true if video playback is in progress


PauseTheora()

Pauses the Theora video playback


ResumeTheora()

Resumes a paused Theora video playback


IsTheoraPaused()

Queries whether the entity is currently playing a Theora video and the playback is paused

Возвращаемое значение

Returns true if video playback is paused


TakeItem(ItemName, InsertAfter)

Добавляет предмет в инвентарь.

Параметры

ItemName
Имя предмета.
InsertAfter
Имя предмета, после которого следует вставить данный предмет (необязательный параметр).

DropItem(ItemName)

Удаляет предмет из инвентаря.

Параметры

ItemName
Имя предмета.

GetItem(ItemIndex)
GetItem(ItemName)

Возвращает ссылку на предмет инвентаря.

Параметры

ItemIndex
Индекс взятого предмета.
ItemName
Имя предмета.

Возвращаемое значение

Ссылка на объект item в инвентаре.


HasItem(ItemName)
HasItem(ItemObject)

Выясняет, есть ли в инвентаре объекта (персонажа) указанный предмет.

Параметры

ItemName
Имя предмета.
ItemObject
Ссылка на предмет (объект item).

Возвращаемое значение

Если указанный предмет есть в инвентаре объекта (персонажа), метод вернёт true.

Примечания

Следует обратить внимание, что данный метод ищет предмет в инвентаре только текущего объекта (персонажа), если Вам нужно просмотреть все существующие инвентари, используйте метод Game.IsItemTaken().


Reset()

Cancels the action the object was currently performing (like talking, walking etc.).


IsTalking()

Queries whether the object is currently talking.

Возвращаемое значение

Returns true if the object is talking.


StopTalking()

Cancels object's talking.

Примечания

You can also use StopTalk() abbreviation.


Talk(Text, SoundFilename, Duration, TalkStances, TextAlignment)
TalkAsync(Text, SoundFilename, Duration, TalkStances, TextAlignment)

Makes the object talk.

Параметры

Text
A text to be used as a talk subtitle
SoundFilename
A filename of a sound file to be used (oprtional, default is no sound)
Duration
A subtitle duration in milliseconds (optional, default is 0)
TalkStances
A comma separated list of talk "stances" to be used for the talking (optional, default is random stances)
TextAlignment
A text alignment for the subtitle (0-left, 1-right, 2-center) (optional, default=2)

Примечания

Talk method blocks the script execution until the animation is over, while the TalkAsync method returns immediately. If the duration is set to zero, it's calculated automatically either from the sound file or from the length of the subtitle.


StickToRegion(Region)
StickToRegion(RegionName)

Forces this actor/entity to act like it's inside a given region

Параметры

Region
Reference to a scene region object
RegionName
Name of a scene region

Примечания

Use this method to "lock" a z-order value of an actor or an entity.


SetFont(Filename)

Sets font of this object.

Параметры

Filename
The name of the font to be set.

Возвращаемое значение

If the method succeeds, the return value is true.


GetFont()

Gets a font assigned to this object.

Возвращаемое значение

Returns the filename of currently assigned font.


CreateParticleEmitter()

Initializes the particle emitter attached to this object.

Возвращаемое значение

Returns the reference to the particle emitter object

Примечания

Once initialized with this method, the particle emitter object can be queried using the ParticleEmitter property.


DeleteParticleEmitter()

Deletes the particle emitter attached to this object.

Возвращаемое значение

Returns true if the method succeeded.


PlayAnim(Filename)
PlayAnimAsync(Filename)

Plays an animation.

Параметры

Filename
A filename of a sprite file to be played

Возвращаемое значение

Returns true if the animation has been played successfuly.

Примечания

The PlayAnim method blocks the script execution until the animation is over, while the PlayAnimAsync method returns immediately. For actors, you can also specify an animation set name instead of filename.


ForceTalkAnim(Filename)

Force a special animation to be used for a subsequent Talk call.

Параметры

Filename
A filename of the sprite file to be used as a talking animation

Примечания

This setting has only effect on one subsequent Talk() method call. After the talking is over, the talking animation is reset back to default.


AddAttachment(EntityFile, PreDisplay, OffsetX, OffsetY)

Adds an attached entity to this object.

Параметры

EntityFile
The filename of the entity to be attached.
PreDisplay
Specifies whether the attached entitiy is drawn below the object or on top of it (optional, default=true)
OffsetX
The X offset of the attachment relative to object's position
OffsetY
The Y offset of the attachment relative to object's position

Возвращаемое значение

Returns true is the attachment has been successfuly attached.

Примечания

This method is typically used for attaching a "blob" shadow image to an actor or an entity. The X and Y offset is scaled accordingly to object's current scale.


RemoveAttachment(AttachmentName)
RemoveAttachment(AttachmentIndex)

Removes an attached entity from this object.

Параметры

AttachmentName
The name of the entity to be detached
AttachmentIndex
The index of the attachment to be detached

Возвращаемое значение

Returns true if the attachment has been successfuly detached.


GetAttachment(AttachmentName)
GetAttachment(AttachmentIndex)

Gets a reference to an attached entity object.

Параметры

AttachmentName
The name of the attached entity to be queried
AttachmentIndex
The index of the attachment to be queried

Возвращаемое значение

Returns a reference to the attached entity or null if specified attachement cannot be found.


SkipTo(X, Y)

Перемещает объект в указанную точку.

Параметры

X
Координата X.
Y
Координата Y.

SetCursor(Filename)

Устанавливает стандартный курсор.

Параметры

Filename
Имя файла спрайта, который будет использоваться в качестве указателя.

Возвращаемое значение

Возвращает true в случае успеха.


GetCursor()

Возвращает имя файла спрайта курсора или null, если курсор не задан


GetCursorObject()

Возвращает ссылку на спрайт курсора (объект) или null, если курсор не задан


RemoveCursor()

Удаляет стандартный курсор.


HasCursor()

Выясняет, задан ли стандартный курсор для объекта.

Возвращаемое значение

Возвращает true, если для объекта задан свой собственный стандартный курсор.


AttachScript(Filename)

Выполняет файл сценария и прикрепляет его к объекту.

Параметры

Filename
Имя файла сценария.

Возвращаемое значение

Возвращает true, если сценарий был успешно выполнен.

Примечания

К каждому объекту WME можно прикреплять несколько сценариев.


DetachScript(Filename, KillThreads)

Выгружает из памяти файл сценария и удаляет его связку с объектом.

Параметры

Filename
Имя файла сценария.
KillThreads
Указывает, нужно ли выгружать из памяти всё запущенные экземляры (threads) этого сценария (необязательный параметр, по умолчанию = false)

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.

Примечания

Экземпляры сценария (threads) - это исполняемые в настоящий момент обработчики событий и методы, которые тем или иным образом включают в себя выполнение данного сценария.


IsScriptRunning(Filename)

Выясняет, прикреплён ли указанный файл сценария к объекту.

Параметры

Filename
Имя файла сценария.

Возвращаемое значение

Возвращает true, если указанный сценарий прикреплён к объекту.


CanHandleMethod(MethodName)

Выясняет, поддерживает ли объект метод с указанным именем.

Параметры

MethodName
Название метода.

Возвращаемое значение

Возвращает true, если объект поддерживает метод с указанным именем.


PlaySound(Filename, Looping, LoopStart)
PlaySound(Looping, LoopStart)

Воспроизводит звук. Если имя файла не указано, воспроизводится прикреплённый на настоящий момент звук (если есть).

Параметры

Filename
Имя звукового файла
Looping
Указывает, нужно ли зациклить воспроизведение звука (необязательный параметр, по умолчанию = false).
LoopStart
Позиция в мс, с которой будет начинаться воспроизведение при включённом зацикливании (необязательный параметр, по умолчанию = 0).

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


PlaySoundEvent(Filename, EventName)
PlaySoundEvent(EventName)

Воспроизводит звук и генерирует событие, когда воспроизведение закончится. Если имя файла не указано, воспроизводится прикреплённый на настоящий момент звук (если есть).

Параметры

Filename
Имя звукового файла
EventName
Имя события, которое будет сгенерировано после окончания воспроизведения звука.

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


StopSound()

Останавливает воспроизведение звука (если есть).

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


PauseSound()

Ставит на паузу воспроизведение звука.

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


ResumeSound()

Продолжает воспроизведение после паузы.

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


IsSoundPlaying()

Выясняет, воспроизводится ли в настоящий момент звуковой файл.

Возвращаемое значение

Если звук воспроизводится, метод вернёт true.


SetSoundPosition(Time)

Задаёт текущую позицию для воспроизведения в звуковом файле.

Параметры

Time
Новая позиция в мс

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


GetSoundPosition()

Возвращает текущую позицию для воспроизведения в звуковом файле

Возвращаемое значение

Позиция в мс.


SetSoundVolume(Volume)

Устанавливает громкость звука.

Параметры

Volume
Уровень громкости в процентах.

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.


GetSoundVolume()

Возвращает значение уровня громкости звука.

Возвращаемое значение

Текущий уровень громкости в процентах.


LoadSound(Filename)

Инициализирует звук из файла, подготавливая его к воспроизведению.

Параметры

Filename
Имя звукового файла.

Возвращаемое значение

В случае удачного выполнения, метод вернёт значение true.

Примечания

Этот метод используется для кэширования звуковых файлов. Инициализация звука занимает некоторое время, поэтому желательно разместить её в стартовом сценарии сцены, чтобы метод PlaySound не замедлял игру. Для этой цели и служит метод LoadSound. Чтобы воспроизвести кэшированный звук, нужно просто вызвать метод PlaySound без указания имени файла, например, SomeObject.PlaySound(false);


SoundFXNone()

Удаляет любой звуковой эффект, прикреплённый к объекту.


SoundFXEcho(WetDryMix, Feedback, LeftDelay, RightDelay)

Задаёт эффект эха для любого звука, привязанного к объекту.

Параметры

WetDryMix
Микс влажность/сухость, в процентах (0 - 100)
Feedback
Обратная отдача, в процентах (0 - 100)
LeftDelay
Задержка слева, в мс (1 - 2000)
RightDelay
Задержка справа, в мс (1 - 2000)

Примечания

Пример: actor.SoundFXEcho(50, 50);


SoundFXReverb(InGain, ReverbMix, ReverbTime, HighFreqRTRatio)

Задаёт эффект реверберации для любого звука, привязанного к объекту.

Параметры

InGain
Прирост, в дБ (-96 - 0)
ReverbMix
Реверберация, в дБ (-96 - 0)
ReverbTime
Время реверберации, в мс (0.001 - 3000)
HighFreqRTRatio
Коэффициент высоких частот (0.001 - 0.999)

Примечания

Пример: actor.SoundFXReverb(0, 0, 2000);


ApplyEvent(EventName)

Вызывает указанное событие для объекта.

Параметры

EventName
Имя события.

Возвращаемое значение

Возвращает true, если событие было вызвано успешно.


CanHandleEvent(EventName)

Выясняет, имеет ли объект обработчик для указанного события.

Параметры

EventName
Имя события.

Возвращаемое значение

Возвращает true, если объект может обрабатывать запрашиваемое событие.