Modding:Adding Block Behavior/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "Этот класс предоставляет несколько методов, которые мы можем переопределить. Когда вы использу...")
(Created page with "Блок будет толкать два блока вместо одного, и игрок может тянуть его, крадясь, щелкая правой кно...")
(26 intermediate revisions by the same user not shown)
Line 30: Line 30:
----
----


The method <code>bool OnPlayerInteract(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling)</code> looks to be ideal for our purpose.
Метод <code> bool OnPlayerInteract (IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling) </code> выглядит идеально подходящим для наших целей.


What should it do?
Что это должно сделать?


# Calculate the new position of the block depending on the face the player is looking at
# Рассчитать новую позицию блока в зависимости от стороны, в которую смотрит игрок
# Check if the block can be placed at this position
# Проверить, можно ли разместить блок в этой позиции
# Remove the original block
# Удалить оригинальный блок
# Place the new block using the previously calculated position
# Поместить новый блок, используя ранее рассчитанную позицию


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
     public override bool OnPlayerInteract(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling)
     public override bool OnPlayerInteract(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling)
     {
     {
         // Find the target position
         // Находим целевую позицию
         BlockPos pos = blockSel.Position.AddCopy(blockSel.Face.GetOpposite());
         BlockPos pos = blockSel.Position.AddCopy(blockSel.Face.GetOpposite());


         // Can we place the block there?
         // Можем ли мы разместить блок там?
        if (world.BlockAccessor.GetBlock(pos).IsReplacableBy(block))
if (world.BlockAccessor.GetBlock(pos).IsReplacableBy(block))
         {
         {
             // Remove the block at the current position and place it at the target position
             // Remove the block at the current position and place it at the target position
Line 53: Line 53:
         }
         }


         // Notify the game engine other block behaviors that we handled the players interaction with the block.
         // Сообщаем игровому движку о других действиях блока, которые мы обрабатывали при взаимодействии игроков с блоком.
         // If we would not set the handling field the player would still be able to place blocks if he has them in hands.
         // Если бы мы не установили поле обработки, игрок все равно мог бы размещать блоки, если бы он держал их в руках.
        handling = EnumHandling.PreventDefault;
handling = EnumHandling.PreventDefault;
         return true;
         return true;
    }
}
</syntaxhighlight>
</syntaxhighlight>


== Register ==
== Регистрация ==


In order the register the BlockBehavior we need to create a mod class, override <code>Start(ICoreAPI)</code> and register it with the given name:
Чтобы зарегистрировать BlockBehavior, нам нужно создать класс мода, переопределить <code> Start (ICoreAPI) </code> и зарегистрировать его с заданным именем:


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 77: Line 77:
</syntaxhighlight>
</syntaxhighlight>


== Distribution ==
== Распределение ==


In order to finish everything, open the modtools and type in <code>pack <your mod id></code>. Now you can take the zip file and share it with other people.
Чтобы закончить все, откройте modtools и введите <code> pack <ваш mod id> </ code>. Теперь вы можете взять zip-файл и поделиться им с другими людьми.
* for VS 1.9: [https://wiki.vintagestory.at/images/2/2a/Moving_v1.0.0.zip Moving_v1.0.0.zip]
* Для VS 1.9: [https://wiki.vintagestory.at/images/2/2a/Moving_v1.0.0.zip Moving_v1.0.0.zip]
* for VS 1.6: [https://wiki.vintagestory.at/images/c/cb/Moving.zip Moving.zip]
* Для VS 1.6: [https://wiki.vintagestory.at/images/c/cb/Moving.zip Moving.zip]


== Testing ==
== Тестирование ==


<youtube>8eVG0uQF2xs</youtube>
<youtube>8eVG0uQF2xs</youtube>


= Advanced Behavior =
= Расширенное поведение =


Our behavior is still rather simple, but there are a lot more possibilities. A behavior can have special properties, which can be defined by the blocktype itself.
Наше поведение все еще довольно просто, но возможностей гораздо больше. Поведение может иметь специальные свойства, которые могут быть определены самим типом блока.


== Example ==
== Пример ==


The behavior liquid supports some special properties as shown in this example of the water blocktype:
Поведение жидкости поддерживает некоторые специальные свойства, как показано в этом примере типа водяного блока:


<syntaxhighlight lang="json">
<syntaxhighlight lang="json">
Line 110: Line 110:
</syntaxhighlight>
</syntaxhighlight>


== Parsing properties ==
== Разбор свойств ==


In order to take care of special properties there is a method called <code>Initialize(JsonObject)</code>. Each blocktype creates a new instance of the behavior, so the method can be used to parse the properties.
Чтобы позаботиться о специальных свойствах, существует метод <code> Initialize (JsonObject) </code>. Каждый тип блока создает новый экземпляр поведения, поэтому метод может использоваться для анализа свойств.


So what kind of properties could we add?
Итак, какие свойства мы можем добавить?
* push distance
* толчок расстояние
* pull block if player is sneaking
* собрать блок, если игрок крадется


First of all, we need to override the method in our block behavior class ...
Прежде всего, нам нужно переопределить метод в нашем классе поведения блока ...


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 127: Line 127:
</syntaxhighlight>
</syntaxhighlight>


Additionally we need to add two fields, one for the distance and another one if the player should pull the block while sneaking ...
Кроме того, нам нужно добавить два поля, одно для расстояния и другое, если игрок должен вытащить блок когда крадется ...


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 134: Line 134:
</syntaxhighlight>
</syntaxhighlight>


Now we can parse the two properties like so:
Теперь мы можем проанализировать два свойства следующим образом:


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 143: Line 143:
----
----


The next thing we need to change is the interact method itself, so that it takes care of the distance and the pull properties ...
Следующее, что нам нужно изменить, - это сам метод взаимодействия, чтобы он позаботился о расстоянии и свойствах вытягивания ...
<syntaxhighlight lang="c#">
        public override bool OnPlayerInteract(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling)
        {
            BlockPos pos = blockSel.Position.AddCopy(pull && byPlayer.WorldData.EntityControls.Sneak ? blockSel.Face : blockSel.Face.GetOpposite(), distance);
            if (world.BlockAccessor.GetBlock(pos).IsReplacableBy(block))
            {
                world.BlockAccessor.SetBlock(0, blockSel.Position);
                world.BlockAccessor.SetBlock(block.BlockId, pos);
            }
            handling = EnumHandling.PreventDefault;
            return true;
        }
</syntaxhighlight>


== Adding another block ==
== Добавление другого блока ==


Let's create another block using this behavior, but this time we will configure some additional properties ...
Давайте создадим еще один блок, используя это поведение, но на этот раз мы настроим некоторые дополнительные свойства ...


<syntaxhighlight lang="json">
<syntaxhighlight lang="json">
Line 174: Line 161:
</syntaxhighlight>
</syntaxhighlight>


The block will be pushed two blocks instead of one and the player can pull it by sneaking while right clicking.
Блок будет толкать два блока вместо одного, и игрок может тянуть его, крадясь, щелкая правой кнопкой мыши.


= Mod Download =
= Загрузка мода =


* for VS 1.9: [https://wiki.vintagestory.at/images/7/7b/Advancedmoving_v1.0.0.zip AdvancedMoving_v1.0.0.zip]
* Для VS 1.9: [https://wiki.vintagestory.at/images/7/7b/Advancedmoving_v1.0.0.zip AdvancedMoving_v1.0.0.zip]
* for VS 1.6: [https://wiki.vintagestory.at/images/7/72/AdvancedMoving.zip AdvancedMoving.zip]
* Для VS 1.6: [https://wiki.vintagestory.at/images/7/72/AdvancedMoving.zip AdvancedMoving.zip]






{{Navbox/modding|Vintage Story}}
{{Navbox/modding|Vintage Story}}

Revision as of 12:43, 14 May 2020

Other languages:

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


Введение

Поведение блоков довольно полезно, если вы хотите, чтобы разные блоки действовали одинаково, поскольку вы можете прикрепить к произвольному количеству блоков одно или несколько поведений. Возможно, вы захотите взглянуть на существующие block behaviors перед реализацией своего собственного.

В этом уроке мы создадим новое поведение, которое мы можем прикрепить к блокам, чтобы сделать их подвижными, щелкнув по ним правой кнопкой мыши.

Настройка

Требуется ознакомится со статьёй - Настройка среды для разработки. Кроме того, вам понадобятся ресурсы (тип блока, текстура и файл lang). Вы можете создать свои собственные или использовать готовые: Moving - No CS File.zip

Создание поведения

Итак, прежде всего нам нужно создать само поведение, которое является классом, расширяющим BlockBehavior

class Moving : BlockBehavior
{
    public Moving(Block block) : base(block)
    {
        
    } 
}

Этот класс предоставляет несколько методов, которые мы можем переопределить. Когда вы используете Visual Studio, вы можете найти полный список методов, наведя курсор мыши на «BlockBehavior» и нажав «F12».


Метод bool OnPlayerInteract (IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling) выглядит идеально подходящим для наших целей.

Что это должно сделать?

  1. Рассчитать новую позицию блока в зависимости от стороны, в которую смотрит игрок
  2. Проверить, можно ли разместить блок в этой позиции
  3. Удалить оригинальный блок
  4. Поместить новый блок, используя ранее рассчитанную позицию
    public override bool OnPlayerInteract(IWorldAccessor world, IPlayer byPlayer, BlockSelection blockSel, ref EnumHandling handling)
    {
        // Находим целевую позицию
        BlockPos pos = blockSel.Position.AddCopy(blockSel.Face.GetOpposite());

        // Можем ли мы разместить блок там?
if (world.BlockAccessor.GetBlock(pos).IsReplacableBy(block))
        {
            // Remove the block at the current position and place it at the target position
            world.BlockAccessor.SetBlock(0, blockSel.Position);
            world.BlockAccessor.SetBlock(block.BlockId, pos);
        }

        // Сообщаем игровому движку о других действиях блока, которые мы обрабатывали при взаимодействии игроков с блоком.
        // Если бы мы не установили поле обработки, игрок все равно мог бы размещать блоки, если бы он держал их в руках.
handling = EnumHandling.PreventDefault;
        return true;
 }

Регистрация

Чтобы зарегистрировать BlockBehavior, нам нужно создать класс мода, переопределить Start (ICoreAPI) и зарегистрировать его с заданным именем:

    public class MovingBlocks : ModSystem
    {

        public override void Start(ICoreAPI api)
        {
            base.Start(api);
            api.RegisterBlockBehaviorClass("Moving", typeof(Moving));
        }

    }

Распределение

Чтобы закончить все, откройте modtools и введите pack <ваш mod id> </ code>. Теперь вы можете взять zip-файл и поделиться им с другими людьми.

Тестирование

Расширенное поведение

Наше поведение все еще довольно просто, но возможностей гораздо больше. Поведение может иметь специальные свойства, которые могут быть определены самим типом блока.

Пример

Поведение жидкости поддерживает некоторые специальные свойства, как показано в этом примере типа водяного блока:

	behaviors: [
		{
			name: "FiniteSpreadingLiquid", 
			properties:
			{
				spreadDelay: 150, 
				liquidCollisionSound: "hotmetal", 
				sourceReplacementCode: "obsidian", 
				flowingReplacementCode: "basalt"
			}
		}
	],

Разбор свойств

Чтобы позаботиться о специальных свойствах, существует метод Initialize (JsonObject) . Каждый тип блока создает новый экземпляр поведения, поэтому метод может использоваться для анализа свойств.

Итак, какие свойства мы можем добавить?

  • толчок расстояние
  • собрать блок, если игрок крадется

Прежде всего, нам нужно переопределить метод в нашем классе поведения блока ...

        public override void Initialize(JsonObject properties)
        {
            base.Initialize(properties);
        }

Кроме того, нам нужно добавить два поля, одно для расстояния и другое, если игрок должен вытащить блок когда крадется ...

        public int distance = 1;
        public bool pull = false;

Теперь мы можем проанализировать два свойства следующим образом:

        distance = properties["distance"].AsInt(1);
        pull = properties["pull"].AsBool(false);

Следующее, что нам нужно изменить, - это сам метод взаимодействия, чтобы он позаботился о расстоянии и свойствах вытягивания ...

Добавление другого блока

Давайте создадим еще один блок, используя это поведение, но на этот раз мы настроим некоторые дополнительные свойства ...

	behaviors: [
		{
			name: "Moving",
			properties: {
				"distance": 2,
				"pull": true
			}
		}
	],

Блок будет толкать два блока вместо одного, и игрок может тянуть его, крадясь, щелкая правой кнопкой мыши.

Загрузка мода


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