Скрипты space engineers конструктор

Обновлено: 28.03.2024

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Modding Space Engineers - The Very Basics

This guide serves as a first introduction to modding in Space Engineers (SE). If you've never modded before, or never modded SE before, this is the place to start.

As newcomers to modding a specific game, oftentimes people will not be aware of what can and cannot be modded in the first place. And what use are the greatest plans for a mod if the game developer has disallowed access to the key files needed to make those plans reality? This chapter will expand on the different "dimensions" of modding, which each require their own expertise and tools. Knowing about these different dimensions will allow you to better understand which are relevant for your plans, and which you'd be interested in learning.

  • mention which tools SBC modding is the by far most universal form of modding. "SBC" refers to the file format that most files containing game data are saved in. They are easily readable and very simple to adjust. Most mods will contain SBC files and thus involve SBC modding, even if they primarily fall into one of the other dimensions of modding.

What follows is an example of how the inside of an SBC file looks like. In this case, it's an excerpt of Components.sbc , which defines the Steel Plate -component.

As you can see, the formatting is fairly straightforward and understandable. Of course there will be some - or many - things you don't yet understand, but it's fairly easy to keep an overview and once you know the different terms and what they mean, it's not hard to imagine this being easy to work with.

This is an example of how a script in SE looks like. It's an excerpt of a script used to control the color of the glowing parts on blocks.

Visual Scripting is a form of scripting that does not require the user to write actual code. The code is rather represented in the form of a network of nodes that are connected to each other. As a result, it's much more approachable for newbies, but the tool used to create these visual scripts - Visual Scripting Tool (VST) - is unfortunately still somewhat buggy. Furthermore, while it does not require the user to write actual code, knowledge of algorithms and the logic under which programs operate is still absolutely essential.

Below is a screenshot of the VST with a script loaded into it. You can see the different nodes represented in various colors with the lines connecting them together.


This dimension includes all the shiny things - the things that make good screenshots and that look and sound cool in the game. While it doesn't require as much prior knowledge to produce usable results with, this dimension does instead oftentimes require a lot of different applications to produce content with. While the industry standard is generally very expensive, there are usually alternative applications available that can produce similar results for free - albiet they may require you to clear a couple additional hurdles in the process.

3D modelling is not an easy skill to learn but there are many applications and much more tutorials available on the internet. 3D modelling is creating objects in SE. Be it blocks, tools, components or even player characters - they were all created in a 3D modelling application.

This is a screenshot of the user interface inside the application called "Blender", which is what you'll most likely be using to do your 3D modelling for SE.


As you can see, the colors aren't quite right and the model is not properly aligned but that is a Beacon block in there.

Textures are what give objects in games, and thus SE, color. They can be edited separately from 3D models and require a separate set of applications to mod. This is one of the easier disciplines and a pretty good point to start with should you want to look into modding the game's visuals.

Below is a screenshot of a texture within Adobe Photoshop. This is likely not what you'll be using as it's a paid application, but it still illustrates the setup fairly well.


The picture may look like the texture contains random shapes, but once these are applied to a 3D model, it will look very different.

Audio modding is often forgotten (to be honest, I nearly forgot it myself when writing this guide - even though I've done quite a bit of it) but is nevertheless an important aspect. Creating and editing sound effects requires another separate set of tools, but is fairly straightforward.

This is a screenshot of the application "Audacity". It's what you'll likely be using to edit and create sound effects for SE.


This particular project file contains multiple sound effects.

Setting up a modding environment

Now that we've got an overview over the different dimensions of modding, the next step is to set up a folder structure to make modding easy and streamlined. While you can do modding in a more unorganized fashion perfectly well, structuring everything from the beginning will help you keep an overview and save you a lot of time in the long run.

First off, you need to decide where on your PC you want to keep your modding files. This can be anywhere - on your main drive or any additional ones - as long as it has enough space. Once you have decided on a location, create a folder and name it something along the lines of SE Modding .

Now, download this file and extract it into your new folder. It contains the various subfolders which will make up the structure of the modding folder. It should now look like this:

With many of them having additional subfolders within them.

This modding folder is your new sandbox. This is where you will work on many of the more complex files that go into your mod to then copy them into the individual mods' folders for testing and upload to the workshop. Now right-click on your SE Modding folder and click Pin to Quick access . This will add the folder to the folder tree on the left side of Windows Explorer like so:


As you can see, in my case the folder is just named SE .

Next up is making getting to the relevant folders more convenient. Outside of this one, there are four locations that you will have to navigate to very frequently: Your Space Engineers game folder, the Space Engineers folder in AppData, the Space EngineersModSDK folder and finally the folder where Steam saves all downloaded Workshop mods to. We're going to make navigating to them easier by creating shortcuts to each:

  1. Right-click into your SE Modding folder and go to New --> Shortcut in the context menu.
  2. In the window that opens up, click Browse and browse to the location of your Space Engineers game installation. This is generally located in C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers . I'm going to assume that if you relocated the installation folder, you're able to find it again.
  3. Click Next and name your shortcut SpaceEngineers Game Folder , then select Finish .

Now you are able to simply click on that shortcut to get to the Space Engineers installation folder. Then, after finding what you need in there you can simply select your SE Modding folder from the Quick access bar to go back.

Let's now do the same for the next shortcut: Create the shortcut, but then enter %APPDATA%\SpaceEngineers into the text field next to Browse . Name the shortcut SpaceEngineers AppData .

The ModSDK link we'll have to skip for now because you likely haven't installed that yet. We'll come back to creating the shortcut for that later.

Lastly, the link to the folder where Steam saves downloaded workshop mods to. This one is located in C:\Program Files (x86)\Steam\steamapps\workshop\content\244850 by default. Adjust the link as needed and enter it into the text field next to Browse . Name the shortcut Workshop Mods .

Your folder should now look like this:


Let's now take a quick tour through this folder to expand on why it is set up like it is.

audio - This is where, you guessed it, audio modding is going to happen. The idea is to use the main folder, \audio\ , to save your finished files into, while the \audio\source\ folder holds various source sound files that you use to build the finished audio files. \audio\projects\ is used to hold the "audio projects" file that audio editing applications usually save in by default. Using those projects allows you to go back into editing the same audio later without having to redo everything or somehow edit the previously finished file.

models - This is where you'll be saving all your 3D model-related files. Within this main folder you'll be saving your "project" files such as .blend in the case of Blender usage, as well as any files needed to generate SE's 3D model format ( .mwm ). models\reference\ is where I recommend placing any reference model files that you use to build your own 3D models with. Having them in one place makes them easy to access. models\Textures\ and its subfolders is where we'll be placing SE texture files so that we can easily reference them within the 3D modelling application. This folder structure is important, because having the folders set up like this will ensure the game also knows where to find these texture files. \models\utility is where we'll place various files related to ease the creation of 3D models for SE.

render - This folder is where we'll be saving 3D renders of our new models to. These renders are essential to creating the HUD / GUI icons of our new blocks, items, etc.

scripts - This will be our working folder to create scripts for SE in. Not really much more to say here.

textures - This is where we'll be working on our own textures (as opposed to models\Textures\ , where we place SE's existing textures). In this folder we'll save both the finished texture files as well as the work-in-progress files to. textures\reference\ is where you should save any reference images for your textures. Having them all in one place will make sorting through them for reference and general inspiration much easier.

tools - This is the folder into which we're going to install and place various tools to handle SE files. We'll get back to this in a bit.

tutorials - This folder is not strictly necessary but I do recommend it: If you find guides and tutorials for modding online, save them to this folder via shortcuts or printing them as PDF (or just mark them with bookmarks in your browser). The important part is to keep an overview over what is available and to make sure you can find it again later, should you need it.

With the folders set up, the next step is to expand on the tools that you'll be using for different parts of the modding process. At this point it'll also make sense for you to decide on what dimension you'll want to dive in. If you don't have any plans to do scripting, for example, don't bother with the tools listed for scripting. No matter which you choose, be sure to acquire all the tools listed under General though.

The following tools are used for pretty much any mod you want to put together. Hence it'll make sense for you to get them no matter which modding dimension you want to focus on.

Space Engineers ModSDK

The official Space Engineers ModSDK contains various tools and data that you'll need when working on your mods. There is no direct download link for it as you'll need to install it via Steam:

Go to your library, then at the top click on Games next to the search-field and select Tools from the dropdown menu. Then browse down to the entry named Space Engineers - Mod SDK and install it. Once it's installed, create a shortcut to the folder it is located in and place it in your SE Modding folder. For easy access.

Microsoft Visual Studio Community

While you can edit XML -based files such as SBC s in pretty much any text editor, that's really just making things harder for yourself. Visual Studio offers the full package, for free. It will also serve as the application you'll do your scripting in, should you choose that route. Be sure to download the "Community" edition of the application via the dropdown menu, that's the free one.

Space Engineers Workshop Tool (SEWT)

While it may seem a little daunting and is not absolutely needed, I still heavily recommend getting this one. SEWT makes uploading and updating your mods very easy, provided we do a little setup beforehand. For now, download the latest release (click on Assets and download the ZIP file), then extract it into your [Space Engineers Game folder]\Bin64\ -directory.

  • separate SDK thingy?
  • PB SDK thingy
  • VST

If you're a student, you can get access to 3Ds Max for free. Even if you are though, you might prefer Blender as the vast majority of SE modders use it over 3Ds Max. There is better plugin support for it, so you can skip some steps when creating models for SE. Though the time saved is not large, it adds up over multiple models.

Blender is a free, open source 3D modelling application. While the industry standard is still 3Ds Max, it is gaining popularity quickly. Its interface takes some time to get used to, but there are thousands of tutorials available for Blender, so you'll have a lot of opportunities to learn the application's intricacies.

You can download and install Blender via Steam, but make sure you install the latest 2.79 version - not 2.8. Unfortunately the plugin necessary to work with SE has not been updated to the newest version.

3Ds Max is the industry standard in the games industry. It's a huge thing, incredibly complex and powerful but there are also countless tutorials available for it, some directly from within the application. If you're a student, you can get 3Ds Max for free via the above link, provided you use it non-commercially. Choosing this will mainly make sense if you have previous modelling knowledge in one of the Autodesk products. This application also requires a bit less setup compared to Blender, as it includes a lot of the needed functionality by default, whereas with Blender you'll have to install plugins for it.

Eikester's MWM Builder (MwmB)

MwmB is the tool used to convert models you've created in your 3D application into the format used by the game. It is contained within the ModSDK, but Eikester maintains an improved version of the tool which provides more debug output to tell you if something went wrong - and what.

Download it and place the contents within the [SE Modding folder]\tools\MwmB\ -directory.

Havok Content Tools

The Havok Content Tools is what we need to use to create the collision models for our new 3D models. They contain a standalone application, but we'll mainly be using them from within Blender or 3Ds Max. Note that the Havok only supports fairly outdated 3Ds Max versions though (3Ds Max 2014 being the latest supported one).

Download the version corresponding with your operating system type and install it into the [SE Modding folder]\tools\Havok\ -directory.

This plugin you will only require if you plan to use Blender. Blender does not support the FBX format out of the box, as such you will need to get this plugin to enable that.

Download and place the .exe into the [SE Modding folder]\tools\ -directory.

Balmung's Blender Plugin

This plugin is what makes creating models for SE with Blender much easier. It was originally created by Harag, but Balmung has forked it and maintains it.

Download the .zip file and place it into the [SE Modding folder]\tools\ -directory without unpacking it.

For texture modding the situation is a bit different from 3D modelling: While Gimp is the free option, it also involves more of a hassle in usage as Adobe Photoshop has much better support for the file formats involved. But there unfortunately isn't really a student version of Photoshop or something along those lines, and the subscription needed is fairly pricey.

Gimp is free and open source. It doesn't have as much functionality as Photoshop out of the box, but there are countless plugins available for it that introduce this missing functionality. Gimp does not support DDS texture files in the compression that SE uses ( BC7 ), so we'll have to rely on an external application to convert textures back and forth from DDS to a Gimp-readable format.

Adobe Photoshop is a solid but expensive choice. It doesn't support DDS import or export out of the box, but there's a plugin for it that enables that functionality. We're going to cover that a bit further down.

TexConv is needed to convert textures from the game format to a format usable by Gimp, 3DsMax and Blender. It is included within the ModSDK: Find it in the SpaceEngineersModSDK\Tools\TexturePacking\Tools -directory, and copy the texconv.exe into your [SE Modding folder]\tools\TexConv\ -folder. Also download the above-linked TexConvGUI.exe - it offers a graphical user interface to work with texconv.exe - without it we'd have to work with command lines. You technically do not need this if you work with Photoshop only.

Intel Textureworks Plugin

This is an official Intel plugin for Photoshop. It allows Photoshop to both import and export to the DDS format used by SE directly. Download and install it is you use Photoshop.

Audio modding doesn't really require any additional tools beyond the software to work with sound itself. While SE sound files used to use a specific format, the current version supports .wav , so it's very simple to work with.

Audacity is a great, free program to work with sounds of all kind. I've used it for quite a while and it works perfectly well to create SE sounds, provided you know how to work the program itself of course.

Adobe Audition is the Adobe Creative Suite option for sound modding. Once again, it's paid, thus there will be less people that can use it, but it's also the superior option as a result of being paid. It contains much more functionality than Audacity, but for modding SE either works fine most of the time.

Тема закреплена. Скорее всего, здесь есть важная информация.

Пока разбирался как использовать Action, запилил небольшой защитный скрипт:
Как это работает: ставим поршень с дверью, перед дверью две туррели и сенсор, за дверью еще один сенсор и звуковой блок (динамик), а так же компьютерный блок.
В компе пишем скрипт. Сенсоры должны его запускать (назначить сенсорам на активацию запуск комп. блока).. Ставим туррели в положение Офф, дверь закрываем.
Назначаем имена объектам:
DoorPiston - имя поршня, который открывает/закрывает дверь
DoorSensor - имя сенсора на выходе
CloseSensor - имя сенсора за дверью
DoorTurret - туррель 1
DoorTurret2 - туррель 2
SoundMessage - звуковой блок
Теперь, когда вы (владелец блока) подходите к сенсору, дверь открывается и активируются туррели, затем к другому сенсору - турели деактивируются и дверь закрывается.
Надеюсь кому нибудь этот пример поможет =) Скрипт внизу:

void Main()
// varitables
IMyPistonBase DoorPiston = GridTerminalSystem.GetBlockWithName("DoorPiston") as IMyPistonBase;
IMySensorBlock DoorSensor = GridTerminalSystem.GetBlockWithName("DoorSensor") as IMySensorBlock;
IMySensorBlock CloseSensor = GridTerminalSystem.GetBlockWithName("CloseSensor") as IMySensorBlock;
IMySoundBlock SoundMessage = GridTerminalSystem.GetBlockWithName("SoundMessage") as IMySoundBlock;
IMyLargeInteriorTurret DoorTurret= GridTerminalSystem.GetBlockWithName("DoorTurret") as IMyLargeInteriorTurret; //
IMyLargeInteriorTurret DoorTurret2= GridTerminalSystem.GetBlockWithName("DoorTurret2") as IMyLargeInteriorTurret; //

if (DoorSensor.DetectOwner == true || CloseSensor.DetectOwner == true)
DoorPiston.GetActionWithName("Reverse").Apply(DoorPiston);
DoorTurret.GetActionWithName("OnOff").Apply(DoorTurret);
DoorTurret2.GetActionWithName("OnOff").Apply(DoorTurret2);
SoundMessage.GetActionWithName("PlaySound").Apply(SoundMessage);
>
>

Contents

Introduction

Editor access

Only one player can edit the same script at a time. If someone else has an editor for the current block open and someone else tries to open that block's editor, a notification will be shown that the editor is already open.

Main method

When the editor is opened for first time on a block, the Program constructor and the Main method are present inside the code editor. The code in the editor becomes the body of the Program class definition.

This Main method is the entry point that will be called when executing script. If Main method is removed / renamed, the script will not run and you will be notified in the programmable block details area.

Custom methods/variables can be defined and used, but only the Main method will be called by the program.

Variable lifetime and scoping

There are two types of variables for scripting:

Local (inside the methods) these variables will keep their value only during execution of a method. Value will be “lost” when the method ends. Global (outside the methods) these variables will keep their values during the lifetime of script. For example, if the variable needs to keep its value between separate runs of the script, it needs to be defined outside the methods.

After pressing “Remember & Exit” or “Remember” buttons, the previous script will be overwritten and all Global variables will be lost.

All variables, local and global except for the built-in Storage variable will lose their value or return to their default value when recompiling the code and between saved game loads. The Storage variable is unique in that it will store the data as a string for use between saved sessions and recompile.

Compiling

After compilation, the code is checked for usage of disallowed namespaces and types. In case that check fails, the following dialog is shown: In this case System.IO.Directory was used to delete some directory. This is forbidden and error is shown that “Not allowed type was used in script”.

If compilation and checks pass, a dialog is shown, confirming the checks passed, and the code is saved.

Script execution

Script can be triggered by the following means:

1. By pressing "Run" button in terminal properties of programmable block.

2. By assigning terminal action and manually pressing the action button (1-9) while controlling the grid using cockpit, control station or remote control.

3. By pressing button on a button panel with assigned action "Run".

4. By a timer with assigned action "Run".

5. By another script in another programmable block in the same grid.

Script is executed only on server even if it’s triggered from client. If there is any exception during script execution, all clients will be notified in programmable block details area about failure. In case of exception during script execution, script will not run again unless User opens editor and change script.

Counting of instructions

Whitelist

The types and classes allowed in scripts are restricted. Refer to the Scripting Whitelist to see what you are allowed to use.

Available interfaces

Possible Actions

Currently only terminal actions can be triggered inside scripts. User can access terminal system for grid on which programmable block is located and trigger any terminal action on any block at grid.

Block Classes (Action List)

Same block class for different SubTypeID

Some blocks have the same parent (e.g. in cubeblocks.sbc) and differs only by subtype (e.g. ). This means there is no distinction between these blocks in code.

Example of these blocks is the Cargo Container: there are 3 types of cargo containers in the game: small, medium and large. These three types differ only by the Subtype and Type is the same for them e.g. large cargo container id is:

In this case there is only one class IMyCargoContainer for all types of cargo containers.

Example programs

Hello world

The standard Hello World program in Space Engineers can be written as such:

If this program is entered into a programmable block and run, it will result in "Hello, world!" being displayed in the programmable block's interface on the lower right hand side of the screen.

Getting your position

This program will show the current GPS coordinates of your programming block's position in the world.

Checking a sensor

It's easy to get a sensor to open a door or trigger some other action even without any programming if you just place that action in the sensor's "Setup actions" list. However, triggering an action when a sensor does not detect something is more difficult, and cannot be done with timer blocks. This program will automatically check a sensor every 10 ticks (working out to about 6 times per second) and close a door if the sensor does not detect anything. This can easily be applied to other purposes, like turning off drills when asteroids are not in sensor range.

For this script to work, the sensor must be named "Door Sensor 1" and the door must be named "Door 1". If you configure the sensor to open the door, the door will automatically open when the player enters the sensor range and close when the player leaves the sensor range.

Firing Thrusters

Compilation errors

This is a list (in progress) of known compilation errors and what causes them.


Sigh autocode will be the death of me. Regardless, there are some things that can still be optimized/improved.

Please consider declaring your lists as fields (outside of Main or any other methods). Re-instantiating tons of lists each run will have a performance impact.

Use typed lists for blocks so you don't need to keep casting.

Make ERR_TXT into a StringBuilder. Appending to a string over and over is wasteful. StringBuilders are much better for this purpose.

Your default filter sorts by Me.CubeGrid . Consider doing block.IsSameConstructAs(Me)

Make the signature of Main like so: Main(string argument, UpdateType updateType) .

. and make the code return if the program was not triggered by the desired UpdateType. This stops the code from running in excess if the user accidentally triggers the code some other way, making the timing predictable. Example: if ((updateType & UpdateType.Update10) == 0) return; // First line of main

For checking thruster, wheel, and cargo types, check the SubtypeId rather than the CustomName . The subtype is static while names can change.

The inventory API has been also updated. Use MyInventoryItem as it is more efficient.

Minor: instead of getDegrees , there are built in functions in MathHelper like MathHelper.ToDegrees(double num)

That's all I've got for today.

Your scripts blow VSB out of the water. They do WAY more complex stuff than will ever be possible with autocoding tools. I have a ton of respect for the work you do. I'm not trying to obsolete serious programmers - I only want to help people without coding knowledge set up simple scripts to control their creations. I'm really surprised that there isn't an in-game tool other than timer blocks to set up basic logic. I know getting started with programming isn't so hard, but many people won't try.

I haven't kept up with space engineers for the past year, so I've been really out of the loop on everything. I really really appreciate your feedback, and I'll make an update to address as many of those things as I can. I'm pretty sure I can actually fix all of those without needing to overhaul anything. Thank you!

Здравствуйте. Я хочу рассказать про проектирование и программирование системы управления конечностями в гексаподе, построенном в Space Engineers.

Забегая вперед скажу, что всё, что касается программирования в Space Engineer, будет в следующей статье. В этой я расскажу про обратную кинематику и покажу прототип на HTML Canvas в котором я занимался отладкой алгоритмов.


Предыстория и постановка задачи.

Изначально было построено сочлененное шасси, а затем на нем копательный агрегат. Такая конфигурация обеспечивала контакт всх колес с поверхностью на больших неровностях, в том числе и при скручивании.

image

Вроде такого

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

С чего начнет строить гексапод нормальный человек? Наверное зайдет в игру и начнет строить тело робота с конечностями, а потом думать как это всё оживлять. Но это не наш метод (ц)

Я начал с теории

Для строения ноги была выбрана следующая схема:

Inner joint — внутренний сустав, качающийся по оси рысканья (yaw)
Mid joint и outer joint — внешние суставы, качающиеся по оси тангажа (pitch). Направление отсчета — от основания ноги к концу ноги.


Угол 0 для всех суставов означает, что нога полностью выпрямлена (прямую ногу будет проще строить в игре).

Задача — при заданной целевой точке найти такие углы поворота сустовов, что-бы конец ноги оказался в заданной точке. Значит время вспоминать тригонометрию.

Угол внутреннего сустава можно найти через арктангенс горизонтальных координат цели.


С двумя другими суставами посложнее. У нас есть длина всех суставов. Можно найти угол к горизонту и расстояние между средним суставом и землей, а так-же расстояние до целевой точки.

Дальше через теорему косинусов нужно найти углы треугольника по известным сторонам.

image

Так это выглядит в коде:

Движение

Далее. Робот должен ходить, верно? То-есть мы должны передавать N раз в секунду каждой ноге координаты заданной позиции. С учетом того, что ног 6 и 3 из них двигаются в противофазе получается как-то сложно. Нужно ввести новый уровень абстракции.

А что если мы представим что нога движется по окружности и ей нужно передавать угол обозначающий позицию на этой окружности? Удаление в сторону становится постоянным и нужно передавать только один параметр, меняющийся циклично. Тогда целевые координыты находятся через синус и косинус.

Пока достаточно

Обдумывая как всё будет работать я понял, что задача слишком сложная для того, что-бы всё заработало с первого раза (с дебагом в Space Engineers всё плохо, но об этом в следующей части).

Поэтому я решил написать визуализатор. Мне хотелось его сделать без дополнительных библиотек и иметь возможность запускать его в один клик и без привязки к окружению.
Поэтому был выбран JS + HTML Canvas.

А сейчас нарисуем сову.


Шаг — структура данных для управления ногой:


Но для отрисовки понадобятся еще несколько классов:

Обертка над Canvas:


В классе Leg есть метод для получения текущих координат суставов. Вот эти координаты мы и будем отрисовывать.

Так-же я добавил отрисовку точек, в которых находилась нога в N последних тиков.

И наконец Worker, который будет запускать симуляцию:

Правда миленько?

Здесь видно, что траектория движения ног отличается от окружности. Движение по вертикали напоминает урезанную синусоиду, а движение по горизонтали линейно. Это должно уменьшить нагрузку на ноги.

Теперь несколько пояснений, что происходит в коде.

Как научить робота поворачивать?

Для поворота я рассмотрел 2 ситуации:

Если робот стоит — ноги двигаются по окружности.

Единственное но — движение именно по окружности сильно усложнило-бы код с текущей реализацией. Поэтому ноги двигаются по касательной к окружности.

Когда робот двигается нужно реализовать что-то вроде Ackermann steering geometry с дифференциалом.

image

То-есть длина шага ног, двигающихся по меньшему радиусу, — меньше. А угол поворота — больше.

Что-бы реализовать изменение угла поворота для каждой ноги я придумал следующий алгоритм:

1. Считаем угол от изначального положения ноги к центру робота:


2. Считаем угол от изначального положения ноги к (центру робота + смещение, которое отвечает за поворот — это изменяемый параметр):


3. Поворачиваем шаг на разницу этих углов:


Но это не всё. Еще нужно изменять длину шага. Реализация в лоб — домножать длину шага на изменение расстояния до центра — имело фатальный недостаток — внешние ноги слишком широко шагали и начинали задевать друг друга.

Поэтому пришлось усложнить реализацию:

1. Считаем изменение расстояния до центра для каждой ноги:


0.3 — магическое число

2. Находим отношение между минимальным и максимальным изменением


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


Вот как это работает (gif 2 мегабайта):

→ Поиграться с результатом можно тут

Для более пристального изучения рекомендую сохранить содержимое в html файл и продолжить в любимом текстовом редакторе.

Читайте также: