Modding:Advanced Blocks/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "Класс блока")
(Created page with "Давайте создадим наш класс блока, который, конечно, должен унаследовать класс <code>Block</code>:")
Line 50: Line 50:
=== Класс блока ===
=== Класс блока ===


<div lang="en" dir="ltr" class="mw-content-ltr">
Давайте создадим наш класс блока, который, конечно, должен унаследовать класс <code>Block</code>:
Let's create our block class itself which of course has to extend <code>Block</code>:
</div>
<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
public class TrampolineBlock : Block
public class TrampolineBlock : Block

Revision as of 00:31, 12 November 2023

Other languages:

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

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

Батут

В этом уроке мы создадим что-то более продвинутое. Блок с функциональностью ... батута!

Ассеты блока

Первое, что нам понадобится, - это assets блока. Это довольно просто.

динственное новое свойство - это class:

	class: "trampoline",

Мы создадим этот класс, чтобы дать блоку желаемую функциональность, поэтому убедитесь, что если вы выберете другое имя, оно будет соответствовать приведенному ниже. Вы можете скачать ассеты этого мода отсюда. Все, что вам нужно сделать, это поместить этот zip-файл в каталог assets вашего проекта разработки.

Класс блока

Теперь нам нужно зарегистрировать наш класс и поэтому нам нужно создать новый файл *.cs в нашем проекте. Назовём его Trampoline.cs.

Система мода

Для создания мода вашему классу необходимо унаследоваться от ModSystem. Это позволит использовать для регистрации кучу всякого, но пока что мы будем придерживаться нашего примера.

public class TrampolineMod : ModSystem
{
    
}

Теперь вам нужно переопределить метод Start(ICoreAPI) и зарегистрировать класс. Если вы выбрали другое имя класса, вы должны использовать его вместо Trampoline.

public class TrampolineMod : ModSystem
{
    public override void Start(ICoreAPI api)
    {
        base.Start(api);
        api.RegisterBlockClass("trampoline", typeof(TrampolineBlock));
    }
}

Так как класса TrampolineBlock ещё нет, это место будет отображаться как синтаксическая ошибка.

Класс блока

Давайте создадим наш класс блока, который, конечно, должен унаследовать класс Block:

public class TrampolineBlock : Block
{

}

This should solve all syntax errors.

So how do we implement a bouncy block? It's pretty helpful to take a look at the api documentation to find a proper way to implement it.

The method void onEntityCollide(IWorldAccessor world, Entity entity, BlockPos pos, BlockFacing facing, bool isImpact) seems to be a good way to implement a bouncy functionality. Note that every trampoline block placed in the game will share the same instance of TrampolineBlock. Because that object is shared by multiple blocks, it does not have a field for the block position. That's why the event handler includes the pos parameter.

When should an entity bounce?

  1. The entity should bounce in the moment it lands on top of the block and not if it is standing on it already. Therefore isImpact has to be true
  2. If the entity is colliding vertically. The sides of the block shouldn't push an entity away. So the axis of the facing has to be Y.

How can we make the entity bounce? In order to make an entity bounce, we need to change its direction. Therefore we can simply revert its motion. The faster the entity will be when during the collision the further it will be pushed away. But simply reverting the motion wouldn't be ideal. The entity would never lose its motion and bounce endless. So let's go for something smaller and make the entity lose 20% of its motion each bounce:

entity.Pos.Motion.Y *= -0.8;

If we put everything together it should look like this:

public class TrampolineBlock : Block
{
    public override void OnEntityCollide(IWorldAccessor world, Entity entity, BlockPos pos, BlockFacing facing, Vec3d collideSpeed, bool isImpact)
    {
        if (isImpact && facing.Axis == EnumAxis.Y)
        {
            world.PlaySoundAt(tickSound, entity.Pos.X, entity.Pos.Y, entity.Pos.Z);
            entity.Pos.Motion.Y *= -0.8;
        }
    }
}

Although this code works already, some sound effects would be rather nice. We can implement it by adding a sound link field to our block, which can use to play the game:tick sound.

public AssetLocation tickSound = new AssetLocation("game", "tick");

This tickSound will played every time an entity bounces:

world.PlaySoundAt(tickSound, entity.Pos.X, entity.Pos.Y, entity.Pos.Z);

If you have done everything right, your file should look similar to this:

using Vintagestory.API.Common;
using Vintagestory.API.Common.Entities;
using Vintagestory.API.MathTools;

namespace VSExampleMods
{
    public class TrampolineMod : ModSystem
    {

        public override void Start(ICoreAPI api)
        {
            base.Start(api);
            api.RegisterBlockClass("trampoline", typeof(TrampolineBlock));
        }
    }

    public class TrampolineBlock : Block
    {
        public AssetLocation tickSound = new AssetLocation("game", "tick");

        public override void OnEntityCollide(IWorldAccessor world, Entity entity, BlockPos pos, BlockFacing facing, Vec3d collideSpeed, bool isImpact)
        {
            if (isImpact && facing.Axis == EnumAxis.Y)
            {
                world.PlaySoundAt(tickSound, entity.Pos.X, entity.Pos.Y, entity.Pos.Z);
                entity.Pos.Motion.Y *= -0.8;
            }
        }
    }
}

Of course you can download the file directly Trampoline.cs.

Testing

Finally we can run our first test. Looks pretty good, right?

Hint: Use the client command .tfedit if you want to adjust the block position, rotation and scale in Hands, in GUI, when dropped on the ground or in third person mode.

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

Here is my version:

Moving Forward

Now that you've successfully made an advanced block you can go even further by learning how to utilize Block Entities and how to create your own Block Behaviors. Both of these tutorials will teach you how to add even more mechanics to your custom blocks.

Or, you can try out making an Advanced Item if you haven't already.

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