Modding:Block and Item Interactions/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "{{GameVersion|1.19.3}}")
No edit summary
 
(17 intermediate revisions by the same user not shown)
Line 3: Line 3:
{{GameVersion|1.19.3}}
{{GameVersion|1.19.3}}


<div lang="en" dir="ltr" class="mw-content-ltr">
Этот урок познакомит вас с основами создания пользовательских взаимодействий. Мы создадим волшебную палочку, которая будет создавать частицы при нажатии правой кнопки мыши.
This tutorial will introduce you into the basics of custom interactions. We will create a magic wand which will spawn particles when holding right click.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
= Подготовка =
= Preparations =
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Я настоятельно рекомендую сначала прочитать о [[Modding:Advanced Items|Классах Предмета]]. Кроме того, вы можете скачать необходимые ассеты [https://wiki.vintagestory.at/images/4/4d/MagicWand_-_No_CS_File.zip здесь].
I highly recommend to read about [[Advanced Items|The Item Class]] first. Additionally you can download the assets [https://wiki.vintagestory.at/images/4/4d/MagicWand_-_No_CS_File.zip here].
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Все это уже должно быть вам знакомо: создание и регистрация класса предмета ...
All of this should be familiar to you, creating and registering the item class ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 37: Line 29:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
== Добавление частиц ==
== Adding particles ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Теперь нам нужно реализовать функцию взаимодействия. Прежде всего нам нужно указать, что игрок может "использовать" этот инструмент, поэтому нам нужно установить handling в <code>handled</code> ...
Now we need to implement the interact function. First of all we need to specify that the player can "use" this tool, therefore we need to set handling to <code>handled</code> ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 52: Line 40:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Метод <code>OnHeldInteractStep</code> позволяет нам создавать частицы за тик, до тех пор, пока игрок использует предмет, но лучше перед этим реализовать анимацию. Частицы должны появляться после завершения анимации ...
The method <code>OnHeldInteractStep</code> allows us to spawn particles per tick while the player is using the item, but it would be better to implement an animation first. Particles should spawn after the animation is done ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 72: Line 58:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Удерживая правую кнопку мыши ...
Holding rightclick ...
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
[[File:Magic Stick Interact.gif|300px]]
[[File:Magic Stick Interact.gif|300px]]
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Итак, давайте начнем работу с частицами, нам нужен статический тип частиц...
So let's start to mess around with particles, therefore we need a static particle type ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 100: Line 80:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Частицы должны появиться после завершения анимации. Это произойдет через <code>0.6</code> секунд ...
Particles should spawn once the animation is completed. This will be the case after <code>0.6</code> seconds ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 111: Line 89:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Рекомендую сначала прочитать руководство по [[Modding:Simple Particles|Простым Частицам]]. Этот код будет создавать частицы перед игроком с рандомизированным цветом и синусоидально изменяющегося размера ...
I suggest to read the tutorial about [[Simple Particles]] first. This code will spawn particles in front of the player with a randomized color and a sinus evolving size ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 132: Line 108:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Если мы соберем все вместе, то метод <code>OnHeldInteractStep</code> будет выглядеть следующим образом...
If we put everything together the <code>OnHeldInteractStep</code> method will look like this ...
</div>


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
Line 170: Line 144:
</syntaxhighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
== Тестирование ==
== Testing ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Теперь мы можем запустить наш первый тест, не правда ли, это выглядит прекрасно?
Now we can run our first test, doesn't it look beautiful?
</div>


<youtube>bTPXL97Gfns</youtube>
<youtube>bTPXL97Gfns</youtube>


<div lang="en" dir="ltr" class="mw-content-ltr">
= Скачать Мод =
= Mod Download =
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Не стесняйтесь попробовать это самостоятельно:
Feel free to try it out yourself:
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Варианты мода из этого руководства:  
Here is my version:  
* for VS v1.9: [https://wiki.vintagestory.at/images/7/72/Magicwand_vs1.9_v1.0.0.zip Magicwand_vs1.9_v1.0.0.zip]
* for VS v1.9: [https://wiki.vintagestory.at/images/7/72/Magicwand_vs1.9_v1.0.0.zip Magicwand_vs1.9_v1.0.0.zip]
* for VS v1.8: [https://wiki.vintagestory.at/images/3/38/MagicWand.zip MagicWand.zip]
* for VS v1.8: [https://wiki.vintagestory.at/images/3/38/MagicWand.zip MagicWand.zip]
</div>






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

Latest revision as of 18:19, 25 March 2024

Other languages:

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


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

Подготовка

Я настоятельно рекомендую сначала прочитать о Классах Предмета. Кроме того, вы можете скачать необходимые ассеты здесь.

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

    public class Magic : ModSystem
    {

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

    }

    public class ItemMagicWand : Item
    {
        
    }

Добавление частиц

Теперь нам нужно реализовать функцию взаимодействия. Прежде всего нам нужно указать, что игрок может "использовать" этот инструмент, поэтому нам нужно установить handling в handled ...

        public override void OnHeldInteractStart(ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel, bool firstEvent, ref EnumHandHandling handling)
        {
            handling = EnumHandHandling.Handled;
        }

Метод OnHeldInteractStep позволяет нам создавать частицы за тик, до тех пор, пока игрок использует предмет, но лучше перед этим реализовать анимацию. Частицы должны появляться после завершения анимации ...

        public override bool OnHeldInteractStep(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (byEntity.World is IClientWorldAccessor)
            {
                ModelTransform tf = new ModelTransform();
                tf.EnsureDefaultValues();

                tf.Origin.Set(0, -1, 0);
                tf.Rotation.Z = Math.Min(30, secondsUsed * 40);
                byEntity.Controls.UsingHeldItemTransformAfter = tf;
            }
            return true;
        }

Удерживая правую кнопку мыши ...

Magic Stick Interact.gif

Итак, давайте начнем работу с частицами, нам нужен статический тип частиц...

        public static SimpleParticleProperties particles = new SimpleParticleProperties(
                    1, 1,
                    ColorUtil.ColorFromRgba(220, 220, 220, 50),
                    new Vec3d(),
                    new Vec3d(),
                    new Vec3f(-0.25f, 0.1f, -0.25f),
                    new Vec3f(0.25f, 0.1f, 0.25f),
                    1.5f,
                    -0.075f,
                    0.25f,
                    0.25f,
                    EnumParticleModel.Quad
                );

Частицы должны появиться после завершения анимации. Это произойдет через 0.6 секунд ...

                if (secondsUsed > 0.6)
                {
                    //Spawn particles
                }

Рекомендую сначала прочитать руководство по Простым Частицам. Этот код будет создавать частицы перед игроком с рандомизированным цветом и синусоидально изменяющегося размера ...

                    Vec3d pos =
                            byEntity.Pos.XYZ.Add(0, byEntity.LocalEyePos.Y, 0)
                            .Ahead(1f, byEntity.Pos.Pitch, byEntity.Pos.Yaw)
                        ;

                    Vec3f speedVec = new Vec3d(0, 0, 0).Ahead(5, byEntity.Pos.Pitch, byEntity.Pos.Yaw).ToVec3f();
                    particles.MinVelocity = speedVec;
                    Random rand = new Random();
                    particles.Color = ColorUtil.ColorFromRgba(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), 255);
                    particles.MinPos = pos.AddCopy(-0.05, -0.05, -0.05);
                    particles.AddPos.Set(0.1, 0.1, 0.1);
                    particles.MinSize = 0.1F;
                    particles.SizeEvolve = EvolvingNatFloat.create(EnumTransformFunction.SINUS, 10);
                    byEntity.World.SpawnParticles(particles);

Если мы соберем все вместе, то метод OnHeldInteractStep будет выглядеть следующим образом...

        public override bool OnHeldInteractStep(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (byEntity.World is IClientWorldAccessor)
            {
                ModelTransform tf = new ModelTransform();
                tf.EnsureDefaultValues();

                tf.Origin.Set(0, -1, 0);
                tf.Rotation.Z = Math.Min(30, secondsUsed * 40);
                byEntity.Controls.UsingHeldItemTransformAfter = tf;

                if (secondsUsed > 0.6)
                {
                    Vec3d pos =
                            byEntity.Pos.XYZ.Add(0, byEntity.LocalEyePos.Y, 0)
                            .Ahead(1f, byEntity.Pos.Pitch, byEntity.Pos.Yaw)
                        ;

                    Vec3f speedVec = new Vec3d(0, 0, 0).Ahead(5, byEntity.Pos.Pitch, byEntity.Pos.Yaw).ToVec3f();
                    particles.MinVelocity = speedVec;
                    Random rand = new Random();
                    particles.Color = ColorUtil.ColorFromRgba(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), 255);
                    particles.MinPos = pos.AddCopy(-0.05, -0.05, -0.05);
                    particles.AddPos.Set(0.1, 0.1, 0.1);
                    particles.MinSize = 0.1F;
                    particles.SizeEvolve = EvolvingNatFloat.create(EnumTransformFunction.SINUS, 10);
                    byEntity.World.SpawnParticles(particles);
                }
            }
            return 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