Modding:Block Entity/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "Вы можете загрузить активы [https://wiki.vintagestory.at/images/d/d4/Ticking_-_No_CS_File.zip здесь] и поместить их в папку с модами.")
No edit summary
Line 13: Line 13:
</syntaxhighlight>
</syntaxhighlight>


Вы можете загрузить активы [https://wiki.vintagestory.at/images/d/d4/Ticking_-_No_CS_File.zip здесь] и поместить их в папку с модами.
Вы можете загрузить ассеты [https://wiki.vintagestory.at/images/d/d4/Ticking_-_No_CS_File.zip здесь] и поместить их в папку с модами.


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">

Revision as of 06:49, 17 October 2022

Эта страница проверялась в последний раз для версии Vintage Story 1.16.

Other languages:

Введение

Блочная сущность — это конструкция, которую вы можете прикрепить к существующему блоку, чтобы придать ему дополнительную функциональность. Всякий раз, когда блок должен что-то делать через регулярные промежутки времени или хранить дополнительную информацию, например содержимое блока сундука, вам нужна сущность блока. Настоятельно рекомендуется прочитать руководство по базовым блокам и классам блоков, чтобы правильно понять это руководство.

Переключатель текстур

Давайте создадим блок, который меняет свою текстуру каждые 3 секунды. Он должен иметь два варианта: "on" и "off". Кроме того, нам нужно определить класс blockentity следующим образом:

	entityClass: "tickingcounter",

Вы можете загрузить ассеты здесь и поместить их в папку с модами.

The BlockEntity

Now we need to register our blockentity class and therefore we need to create a new *.cs file in our project. Let's name it Ticking.cs.

First of all you need to create the blockentity class itself. Therefore you need to extend BlockEntity:

    public class TickingBlockEntity : BlockEntity
    {
    
    }

This class needs to have a timer, once the timer reaches 3 seconds it should replace the current block with the different state.

In order to create a timer we need to register a tick listener. Therefore we need to override Initialize(ICoreAPI):

        public override void Initialize(ICoreAPI api)
        {
            base.Initialize(api);
        }

add a counter (which should increase per tick) ...

        public float timer;

... and the actual ticking method ...

        public void OnGameTick(float dt)
        {
        
        }

To register the ticking method we can use RegisterGameTickListener in Initialize

        public override void Initialize(ICoreAPI api)
        {
            base.Initialize(api);
            RegisterGameTickListener(OnGameTick, 50);
        }

The timer itself should increment by dt, the time difference in seconds between the current tick and the previous tick. It ticks about every 50ms or less often if the game is slow. So if the timer is greater than 3, it should replace the block:

        public void OnGameTick(float dt)
        {
            timer += dt;
            if(timer >= 3)
            {
                Block block = Api.World.BlockAccessor.GetBlock(Pos);
                if (block.Code.Path.EndsWith("-on"))
                {
                    block = Api.World.GetBlock(block.CodeWithParts("off"));
                }
                else
                {
                    block = Api.World.GetBlock(block.CodeWithParts("on"));
                }
</div>

                <div lang="en" dir="ltr" class="mw-content-ltr">
Api.World.BlockAccessor.SetBlock(block.BlockId, Pos);
            }
        }

Furthermore we need to save the current time:

        public override void ToTreeAttributes(ITreeAttribute tree)
        {
            base.ToTreeAttributes(tree);
            tree.SetFloat("timer", timer);
        }
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
public override void FromTreeAttributes(ITreeAttribute tree, IWorldAccessor worldForResolving)
        {
            base.FromTreeAttributes(tree, worldForResolving);
            timer = tree.GetFloat("timer");
        }
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">

Registering the Block Entity

Registering the blockentity class is rather simple (rather similar to registering a block class). You need a mod class and override Start(ICoreAPI):

    public class Ticking : ModSystem
    {
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
public override void Start(ICoreAPI api)
        {
            base.Start(api);
            api.RegisterBlockEntityClass("tickingcounter", typeof(TickingBlockEntity));
        }
</div>

    <div lang="en" dir="ltr" class="mw-content-ltr">
}

Testing

Now everything is ready to run the first test:

Distribution

In order to finish everything, open the modtools and type in pack <your mod id>. Now you can take the zip file and share it with other people. It will work in the same way as ordinary mods, you can install it by copying it into the mods folder.

Mod Download


Icon Sign.png

Wondering where some links have gone?
The modding navbox is going through some changes! Check out Navigation Box Updates for more info and help finding specific pages.

Modding
Modding Introduction Getting Started Пакет тем
Content Modding Content Mods Developing a Content Mod Basic Tutorials Intermediate Tutorials Advanced Tutorials Content Mod Concepts
Code Modding Code Mods Setting up your Development Environment
Property Overview ItemEntityBlockBlock BehaviorsBlock ClassesBlock EntitiesBlock Entity BehaviorsWorld properties
Workflows & Infrastructure Modding Efficiency TipsMod-engine compatibilityMod ExtensibilityVS Engine
Additional Resources Community Resources Modding API Updates Programming Languages List of server commandsList of client commandsClient startup parametersServer startup parameters
Example ModsAPI DocsGitHub Repository