Modding:Advanced Blocks/ru: Difference between revisions
(Created page with "Система мода") |
(Created page with "Для создания мода вашему классу необходимо унаследоваться от <code>ModSystem</code>. Это позволит использовать для регистрации кучу всякого, но пока что мы будем придерживаться нашего примера.") |
||
Line 24: | Line 24: | ||
=== Система мода === | === Система мода === | ||
Для создания мода вашему классу необходимо унаследоваться от <code>ModSystem</code>. Это позволит использовать для регистрации кучу всякого, но пока что мы будем придерживаться нашего примера. | |||
<syntaxhighlight lang="c#"> | <syntaxhighlight lang="c#"> |
Revision as of 00:27, 12 November 2023
Эта страница проверялась в последний раз для версии Vintage Story 1.15.
Настоятельно рекомендуется сначала прочитать про базовые блоки . Кроме того, это руководство требует среды разработки. Если у вас её еще нет, прочтите руководство по настройке среды для разработки .
Батут
В этом уроке мы создадим что-то более продвинутое. Блок с функциональностью ... батута!
Ассеты блока
Первое, что нам понадобится, - это assets блока. Это довольно просто.
динственное новое свойство - это class
:
class: "trampoline",
Мы создадим этот класс, чтобы дать блоку желаемую функциональность, поэтому убедитесь, что если вы выберете другое имя, оно будет соответствовать приведенному ниже. Вы можете скачать ассеты этого мода отсюда. Все, что вам нужно сделать, это поместить этот zip-файл в каталог assets
вашего проекта разработки.
Класс блока
Теперь нам нужно зарегистрировать наш класс и поэтому нам нужно создать новый файл *.cs
в нашем проекте. Назовём его Trampoline.cs
.
Система мода
Для создания мода вашему классу необходимо унаследоваться от ModSystem
. Это позволит использовать для регистрации кучу всякого, но пока что мы будем придерживаться нашего примера.
public class TrampolineMod : ModSystem
{
}
Now you need to override the Start(ICoreAPI)
method and register the class. If you have picked a different class name you have to use that one instead of trampoline.
public class TrampolineMod : ModSystem
{
public override void Start(ICoreAPI api)
{
base.Start(api);
api.RegisterBlockClass("trampoline", typeof(TrampolineBlock));
}
}
This should be marked as a syntax error because there is no TrampolineBlock
class yet.
The Block Class
Let's create our block class itself which of course has to extend 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?
- 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 betrue
- If the entity is colliding vertically. The sides of the block shouldn't push an entity away. So the
axis
of thefacing
has to beY
.
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:
- for VS v1.9: Trampoline_vs1.9_v1.0.0.zip
- for VS v1.5: Trampoline.zip
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.
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 | Item • Entity • Block • Block Behaviors • Block Classes • Block Entities • Block Entity Behaviors • World properties |
Workflows & Infrastructure | Modding Efficiency Tips • Mod-engine compatibility • Mod Extensibility • VS Engine |
Additional Resources | Community Resources • Modding API Updates • Programming Languages • List of server commands • List of client commands • Client startup parameters • Server startup parameters Example Mods • API Docs • GitHub Repository |