Gamemaker studio 2.3: new gml features

Maths

  • matrix_build_identity() — return an identity matrix
  • matrix_build_lookat(xfrom,yfrom,zfrom,xto,yto,zto,xup,yup,zup) — builds a «look-at» (view) matrix for a camera at position (xfrom, yfrom, zfrom) and looking at a point (xto, yto, zto) with an up vector of (xup, yup, zup)
  • matrix_build_projection_ortho(width,height,znear,zfar) — build an orthographic projection matrix with width, height and a z range from znear to zfar
  • matrix_build_projection_perspective(width,height,znear,zfar) — build a perspective matrix with width, height and a z range from znear to zfar
  • matrix_build_projection_perspective_fov(fov_y,aspect,znear,zfar)- build a perspective matrix with field of view ange fov_y and an aspect ration and a z range from znear to zfar
  • matrix_transform_vertex(matrix, x, y, z, ) — multiply the given vector (x,y,z,w) by the matrix NOTE: if no w component given then it is treated as 1
  • matrix_stack_push(optional_matrix) — push matrix onto the matrix stack
  • matrix_stack_pop() — pop matrix from the top of the matrix stack
  • matrix_stack_set(matrix) — set the given matrix as the top of the matrix stacl
  • matrix_stack_clear() — clear the matrix stack
  • matrix_stack_top() — return the value at the top of the matrix
  • matrix_stack_is_empty() — return true if matrix stack is empty, false otherwise

Summary

As you may imagine, this is a rather important update to GameMaker Studio 2 with a lot of new features and a lot of changes «under the hood» to make life easier and to make the product easier to use and more compatible with things like source control. We’ve said it already during in this blog post, but it’s worth repeating… read the manual! This is especially important when starting to use the new Sequences asset, as the editor has a lot to it and — especially if you are not an artist or have never used any kind of animation or video editing software — it can be a bit overwhelming to start with. However, we think this is an incredibly powerful tool and opens up GameMaker Studio 2 in a big way to people who are less experienced with code and who prefer a more visual approach to making games.

One final thing should be said about importing pre-2.3 projects. On importing a project made with a version of GameMaker Studio 2 prior to this update, you will be prompted to save the project again using a new name before continuing. This is absolutely essential as the changes made to the project file format are not backwards compatible and once you update a project to 2.3 it can’t be loaded into previous versions, so it’s a good idea to keep separate folders for pre and post 2.3 versions of any game you are working on.

Thanks for reading and we can’t wait to see what you all do with the new features!

Happy GameMaking!

View Ports

  • room_set_viewport(room_ind,vind,vis,xport,yport,wport,hport) — set the viewport for a specific view in a specific room
  • room_get_viewport(room_ind,vind) — get the viewport for a specific view in a specific room (returns array — xport, — yport, — wport, — hport)
  • room_get_camera(room_ind,vind) — get the camera for a specific view in a specific room
  • room_set_camera(room_ind,vind,camera) — set the camera for a specific view in a specific room
  • view_get_camera(view) — get the camera for a view in the current room
  • view_get_visible(view) — get the visible status for a the view in the current room
  • view_get_xport(view) — get the xport for the view in the current room
  • view_get_yport(view) — get the yport for the view in the current room
  • view_get_wport(view) — get the wport for the view in the current room
  • view_get_hport(view) — get the hport for the view in the current room
  • view_get_surface_id(view) — get the surface_id for the requested view in the current room
  • view_set_camera(view,camera) — set the camera for a view in the current room
  • view_set_visible(view,visible) — enable or disable the visibility of a view in the current room
  • view_set_xport(view,xport) — set the xport of the view in the current room
  • view_set_yport(view,yport) — set the yport of the view in the current room
  • view_set_wport(view,wport) — set the wport of the view in the current room
  • view_set_hport(view,hport) — set the hport of the view in the current room
  • view_set_surface_id(view,surface_id) — set the surface_id for the view in the current room

Становимся профессионалом

Несколько GameMaker игр стали коммерчески успешными, и есть много других великолепных GameMaker игр, которые являются прекрасными примерами того, что возможно создать используя GM:S.

Отточеные игры

Spelunky — оригинальная версия Spelunky была создана в GameMaker; более новая XBLA версия и новая ПК-версия игры, нет. Это коммерческий успех, версия, созданная в GameMaker, бесплатная.

A Nation of Wind — эта игра скрытый драгоценный камень и в нее стоит определенно поиграть.

Dustforce — вышла в Steam, это не был огромный коммерческий успех, но тем не менее, это отличная игра!

Особенности

GameMaker: Studio позволяет писать расширения под множество платформ на соответствующих им языках. Поддерживаются следующие типы файлов расширений: gml везде, dll-библиотеки на Windows, Windows Phone, Xbox One, js-скрипты для HTML5, so-библиотеки на Linux и Tizen, dylib-библиотеки на Mac, prx на PS4, suprs на PSVita, а также специальные placeholder для iOS и Android. Есть возможность создать прокси-расширения для проектов на многих платформах, что позволяет использовать одинаковые названия функций в коде, но обращаться к библиотекам соответствующей платформы.

Имеются функции для работы с кодировками Base64, JSON, MD5, SHA-1, возможности распаковки ZIP-архивов, чтения и записи .ini, текстовых и двоичных файлов, управления каталогами. Есть возможность взаимодействовать с сетью: коллективная игра по UDP, TCP, Bluetooth, отправка http-запросов, загрузка любых файлов, взаимодействие со Steam API и .

С версии 1.1.1086 добавлена поддержка шейдеров — эффективного инструмента управления отрисовкой, добавления графических эффектов и преобразований. GameMaker: Studio поддерживает вершинные и фрагменты шейдеры на языках GLSL ES, HLSL9, HLSL11 и GLSL.

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

GameMaker: Studio содержит множество математических функций для работы со скалярными и векторными величинами, включая тригонометрические вычисления, нахождение степеней, логарифмов, интерполяций, нормалей векторов, скалярных произведений. Имеется встроенный физический движок Box2D, набор функций для работы с ним, демонстрационные проекты Angry Cats и Angry Cats Space.

В отличие от GameMaker, Studio использует компилятор, а не интерпретатор кода, что убрало возможность выполнения чистого кода «на лету», но существенно увеличило производительность игр. Также есть дополнительный модуль YoYoCompiler, транслирующий GML-код в C++ и оптимизирующий его. Проекты, собранные с использованием этого компонента, показывают хорошую производительность с сотнями игровых элементов на уровне. Однако этот модуль доступен не для всех платформ.

Присутствует поддержка многих сервисов монетизации (таких как AdMob, Google Analytics, Google Play Licensing) из кода. Также имеется поддержка систем управления версиями — есть примеры интеграции с SVN, GIT, Mercurial.

В последних версиях появилось множество опций отладки программ в новом окне The Debug Module, позволяющих ставить точки остановки, следить за выполнением кода, значениями любых переменных, конкретных объектов, содержимым буферов, количеством и временем выполнения разных скриптов.

Camera functions

  • camera_create() — create a camera
  • camera_create_view(room_x,room_y,width,height,angle,object,x_speed,y_speed,x_border,y_border) — create a camera with settings for a view in a room
  • camera_destroy(camera) — destroy the given camera
  • camera_apply(camera) — apply the camera settings to the current camera
  • camera_get_active() — get the current active camera
  • camera_get_default() — get the current default camera (camera used when there are no views active)
  • camera_set_default(camera) — set the given camera as the default camera
  • camera_set_view_mat(camera,matrix) — set the view matrix of the given camera
  • camera_set_proj_mat(camera,matrix) — set the projection matrix of the given camera
  • camera_set_update_script(camera,script) — set the update script to use on the given camera
  • camera_set_begin_script(camera,script) — set the begin script to use on the given camera
  • camera_set_end_script(camera,script) — set the end script to use on the given camera
  • camera_set_view_pos(camera,x,y) — set the view position on the given camera
  • camera_set_view_size(camera,width,height) — set the view size on the given camera
  • camera_set_view_speed(camera,x_speed,y_speed) — set the view speed on the given camera
  • camera_set_view_border(camera,x_border,y_border) — set view the border size on the given camera
  • camera_set_view_angle(camera,angle)- set view the angle on the given camera
  • camera_set_view_target(camera,object) — set the target object for the given camera
  • camera_get_view_mat(camera) — get the view matrix for the given camera
  • camera_get_proj_mat(camera) — get the projection matrix for the given camera
  • camera_get_update_script(camera) — get the update script for the given camera
  • camera_get_begin_script(camera) — get the begin script for the given camera
  • camera_get_end_script(camera) — get the end script for the given camera
  • camera_get_view_x(camera) — get the view pos x value for the given camera
  • camera_get_view_y(camera) — get the view pos y value for the given camera
  • camera_get_view_width(camera) — get the view width for the given camera
  • camera_get_view_height(camera) — get the view height for the given camera
  • camera_get_view_speed_x(camera) — get the view speed x for the given camera
  • camera_get_view_speed_y(camera) — get the view speed y for the given camera
  • camera_get_view_border_x(camera) — get the view border x for the given camera
  • camera_get_view_border_y(camera) — get the view border y for the given camera
  • camera_get_view_angle(camera) — get the view angle for the given camera
  • camera_get_view_target(camera) — get the view target object for the given camera

Возможности

Изначально автор приложения – Марк Овермарс – хотел создать обучающую программу, которая объясняла бы студентам принципы программирования. Однако постепенно разработка превратилась в игровой редактор. Он развивается уже более 15 лет, обрастая функционалом, что позволяет:

  • придумывать 2D-игры;
  • создавать презентации;
  • рисовать анимацию;
  • использовать программу в учебных целях.

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

Используемые принципы игростроения

Возможностей редактора хватает для создания игр, подобных тетрису, арконоиду, пэкмену и т.д. Можно создать и красивые аркады, если задействовать творческий потенциал на всю мощь – функции приложения это позволяют. Все элементы, используемые программой для создания игры, называются ресурсами. К ним относятся:

  • спрайты;
  • объекты;
  • комнаты или уровни;
  • звуки;
  • фоны;
  • пути;
  • скрипты;
  • шрифты;
  • тайм-лайны.

Наиболее важными и одновременно простыми в усвоении являются первые пять ресурсов. Остальные четыре требуют дополнительного изучения, они помогают усовершенствовать игру.

Спрайтами называются изображения, которые используются для отображения на экране объектов. Другими словами – это картинки или анимации. Их можно нарисовать в самой программе или загрузить из внешних источников, например, большой встроенной библиотеки. Они могут иметь формат .png или .gif.

Объекты – основная составляющая игр. Это герои, враги, стены, препятствия, окружающие предметы мира и т.д. Объектам могут задаваться действия, например, реакции на нажатие кнопок клавиатуры, мыши или джойстика, реакции на столкновения с другими объектами, действия по умолчанию и т.д. При создании объектов используются принципы объектно-ориентированного программирования, но простота игрового редактора позволяет использовать эти принципы без их глубокого изучения.

Комнаты или уровни – это локации, в которых происходят игровые действия, и в которых находятся объекты. Комнаты плоские, двухмерные, но они могут имитировать и 3D-графику. Уровни можно оформить любым образом, использовать объекты-стены и декорации, загружать фоны и т.д. Можно настроить комнату так, чтобы при выходе все объекты в ней сохранялись или сбрасывались.

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

Программа имеет библиотеку встроенных звуков. Совершая действия, объекты могут издавать те или иные звуки. Кроме встроенных эффектов, можно использовать загруженные звуковые файлы. Кроме спецэффектов, можно загружать и фоновую музыку.

Этих ресурсов достаточно для создания несложных, но увлекательных игр, которые запустятся даже на Windows 10. На воплощение задумки может понадобиться около часа. Чтобы игра засияла новыми гранями и стала глубже и интереснее, все ее элементы можно настроить скриптами, а для придания игровым функциям гибкости используются пути и тайм-лайны. Эти элементы требуют некоторых знаний об информационных технологиях, однако они не обязательны.

Runtime Changes

Many functions have been added in GameMaker Studio 2, the following sections outline those that have been added and those that have been removed, please consult the manual (Help -> Open Manual) for further info.

Our Windows Desktop Runner has also changed from using DX9 to using DX11 this may mean that there are some compatibility issues that may need to be addressed, there are some known issues at present

  • No Anti Aliasing implemented — all functions return 0 for the number of anti aliasing levels, we will implement this in the future
  • Line drawing — unfortunately line drawing is not consistently implemented by hardware vendors, this means that between different manufacturers and different drivers from the same manufacturer you may get different results, we reccomend that you do not rely on line drawing in released games, but the functions are still there for you to try.
  • Windows XP is no longer supported for games created using GameMaker Studio 2.

Расширения

Если вам не хватает встроенных функций движка GameMaker, не волнуйтесь; он расширяемый! Бесплатная версия не позволяет использовать расширения, но в платной версии это возможно.

Что могут делать расширения?

Расширения добавляют новую функциональность, изначально не предусмотренную YoYo games. Вот некоторые примеры:

GiiMote — позволяет разработчику интегрировать WiiMote элементы управления в свою игру, добавляя функции, которые опрашивают состояние WiiMote (положение и нажатие кнопок).

FX Creator Extension — упрощает создание таких эффектов, как погода, лучи и брызги воды.

Взаимодействие с базами данных с помощью SQL — позволяет вашей игре подключиться к базе данных SQL, получить данные в виде строки, а затем использовать их в игре. Расширение
добавляет такие функции, как и так, что вы можете получить данные обратно в виде двух строк кода.

Одно серьезное ограничение — некоторые расширения несовместимы с мобильными платформами.

Как их установить

  1. Необходимо загрузить расширение — это должен быть файл .
  2. Щелкните правой кнопкой мыши папку Extensions в GM:S и выберите Add Existing Extension.
  3. Это должно вызвать диалоговое окно, и в правом нижнем углу вы увидите кнопку с надписью Install. Нажмите ее.
  4. Откроется другое диалоговое окно со списком установленных пакетов (возможно, пустым). Справа от этого окна есть кнопка, которая снова с надписью Install. Нажмите ее.
  5. Это открывает еще одно диалоговое окно; перейдите в папку, в которой сохранен файл , щелкните его и нажмите кнопку Open.

Arrays

The first change to the GameMaker language that we want to discuss is a change to how arrays work. Previously, GML only permitted 1D or 2D arrays, eg:

However, this is no longer the case and now all arrays are 1D. So how do we create a 2D array now? Well this is done by chaining arrays together to essentially create arrays within arrays. Here is a small example:

The above is now a multi-dimension array with 2 dimensions to it, but you are no longer limited to just 2 dimensions and can create arrays of 3 or 4 or more dimensions as required, eg:

This change means that all platforms will now work the same (including HTML5) and enables much larger arrays, both in number of items as well as number of dimensions. The change also means that the following functions have been deprecated:

And the following new functions have been added:

Note that the old functionality (and the deprecated functions mentioned above) will still work but under no circumstances should new projects use the old syntax, as these will eventually be removed from the language.

Structs

The next new feature that we want to discuss in GameMaker Studio 2.3 is the creation of structs. A struct is — to put it simply — a variable that holds a collection of other variables — you can think of it as a kind of «light-weight object». The variables that a struct holds can be of any data type and these variables can be read from and written to after the initial struct declaration, and you can also add more variables to a struct after it has been declared. It should also be noted that the contents of a struct are independent of the instance or script that created it, and as such you can — if you wish — use the built-in variable names like or and . One of the benefits of using structs is that (unlike instances), after the initial creation, structs have no processing overhead while they exist, although they will take up space in memory. The struct syntax is as follows:

So, an example of this in practice would be:

The above creates an instance scope struct in the variable «mystruct» and populates it with some values (structs can be created at local, instance and global scope, just like any other variable). Note that you don’t have to populate the contents of a struct when it is created initially and you can create an empty struct by simply doing this:

This struct can then be added to at a later point in the game code. Here is an example of a struct with various variables and data types:

You’ll notice in the above code that you can also define methods and use runtime functions in structs, and that you can use expressions consisting of any variable previously defined within the context of the struct itself, as well as any variable defined within the scope of the struct itself.

Once a struct has been defined, you can access the data within using the «point» notation, like this:

You can also perform operations on the variables within a structure or use them in functions, just as you would any other variable. For example:

Finally, structs can have other structs nested inside of them, like this:

To access such nested structs you would still use the point notation, like this:

When a struct is no longer required it can be removed from memory using the operator, which is another new GML feature added in the 2.3 update. This de-references the struct and hints to the garbage collector that it may be available for collection. This is not strictly required as the garbage collector may do this automatically in the following game steps if the struct is no longer referenced in your code, but it is good practice to do so and we recommend it (for example, call delete in the Clean Up event of an instance to explicitly tell the garbage collector that an instance scope struct is to be deleted).

Also note that structs can be created using functions, which requires the use of the operator and the keyword (two more new features to GML), as shown in the following example:

Here we are creating the function and telling GameMaker Studio 2 that this is a function for making a struct by adding the keyword after the definition. You can then call this function like this:

Now the variable v1 will reference a struct with the variables x and y and the static method variable .

Note that there are other additional functions for structs, specifically:

Check the manual for details of how these functions should be used.

Где я могу получить GameMaker: Studio?

Основной сайт движка GM:S — это http://www.yoyogames.com/. Вы можете загрузить бесплатную версию или приобрести одну из лицензионных версий.

Ниже приведено сравнение различных версий GameMaker, взятых с веб-сайта YoYo Games:

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

Обновление: Бесплатная версия GameMaker: Studio теперь та же, что и стандартная версия! Для получения дополнительной информации см. GameMaker: Studio будет бесплатной.

Стандартная версия отлично подходит для разработчиков одиночек, которые только планируют разработку компьютерных игр; Профессиональная версия идеально подходит для небольшой команды разработчиков планирующих переходить в конечном итоге на кроссплатформенную разработку, поскольку они могут добавлять различные модули с течением времени после получения некоторого дохода; и Master Collection отлично подойдет для небольших команд, которые являются частью созданных студий, и хотели бы использовать кроссплатформенную разработку с самого начала.

GM:S также
доступен в Steam, но я бы рекомендовал не покупать его там, так как
YoYo Games не знает, что вы его приобрели, и,
следовательно обладателям их продукта будет больше хлопот в отделе обслуживания клиентов. Кроме
того, они иногда предлагают дешевые апгрейды для тех, у кого уже есть определенная версия GM:S, и они не могут дать то же обновление пользователям купившим в Steam. Кроме того, если вы покупаете у Steam, то необходимо войти в Steam, чтобы запустить GM:S, а это может раздражать.

Обзор интерфейса

Последней версией Game maker studio №1 была 8.1.140, на сегодняшний день она перестала поддерживаться, так была выпущена новая версия Game maker studio 2.

Так же на официальном форуме можно скачать русификатор для движка.

Ссылка на русификатор: Google drive

После того как вы скачали и установили Game maker studio запускаем его и в окне вводим данные, которые зарегистрировали на официальном сайте при скачивании. После ввода данных нам открывается интерфейс движка.

Так как мы используем бесплатную версию программы, категория «Изучение» нам не будет доступна.

Для того, чтобы начать разработку игры, нажимаем на кнопку «Создать» и в следующем окне «Drag and Drop» после чего откроется окно, в котором нужно придумать название проекта и сохранить в удобное для вас место.

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

Для того что бы начать работать и создавать объекты нам нужно будет нажать правой кнопкой по пустому пространству, и выбрать пункт «Ресурсы». В выпавшем окне выбираем с создания чего будем начинать разработку.

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

Для создания карты нам нужно выбрать «Ресурсы», а затем в выпавшем окне «Создать комнату». В редакторе комнаты предоставляются возможности задать размер, фон, установить элементы взаимодействия, разместить персонажей, нарисовать пути и т.д. В редакторе комнаты так же можно импортировать уже готовый фон или создать его саму с помощью этого редактора.

Создание событий можно произвести без обращения к программированию и созданию скриптов, все делается с помощью довольно интуитивно понятных меню и окон. Можно продумать и создать довольно сложные сценарии действий для объекта с помощью визуального редактора Game maker studio.

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

Стоит заметить часть программы, в которой нам дается возможность работать с кодом на языке GML. Очень радует та легкость, с которой простые командные функции могут быть сделаны. Поэтому если вы начинающий Game creator и готовы посвятить этому большую часть времени, тогда вам просто необходимо заняться изучением языка GML.

Functions, Scripts and Method Variables

Above we outline some changes to the GameMaker Language, but now it’s time to talk about the good stuff… what’s been added! To start with we want to talk about in-line functions and scripts. Previously, a script was a single resource that was created on a global scope and used to create a single custom function which would then be called using the script name as the function name. This is no longer the case and scripts, while still global in scope, are now a type of «container» for one or more functions.

What this means is that when you compile your project, scripts are no longer called individually, but are actually all run at the start of the game in the global scope, so all variables that are defined in the script (outside of function definitions) will be considered global. That said, you should still use the identifier to explicitly define and identify global variables in your code.

The reason for this change is that scripts can now contain multiple functions. If you’ve only used GML to code projects then the idea of functions may be something new to you, but think of them as being the same as scripts, only explicitly assigned to a variable. This variable is called a method and is used to call the code that is in the function, the same as you would have previously called the script name. This is easier to visualise with an example, so let’s look at one. Consider this simple script :

Now, however, this would be defined as a function like this:

or like this:

You would call this function just as you would have called the script:

So, as we mentioned above, scripts can now contain multiple functions and these should be defined with the format shown above where you have the JS doc comment to identify the function, then the function definition below, and then the next JS Doc comment, and then the function, etc…

Above, we briefly mentioned that functions as variables were called method variables, but it should be explained in a bit more detail. Basically, when you create a function with a variable like this, you are creating a method variable, and they can have different scopes. Consider this function:

  • In the case of a script a variable called «foo» is declared at global scope

  • If the function is declared in an event then the variable «foo» is on the instance that ran that event

  • If the function is declared in an event using the keyword then the variable «foo» is local to the event only

  • If «foo» is declared inside a then it is declared on the that is active at that time

This means that if you have some code that you need to use only within a loop in an alarm event (for example), then you can define it as a local scope method variable at the start of the event and then use it within the loop without the need to clutter up the script assets with it.

It is worth noting that while the variable will be in the chosen scope, the actual function will be bound to the scope that it was initially defined in. Going back to script functions, these are all global scope and are considered «unbound» (ie: they are not associated with any instances), but if you have a script function that creates another function within it and then you call this script from an instance, the function used within the script will be bound to the instance. In general this is not something you ever need to think about but for more complex operations with method variables it’s worth taking into consideration. This also applies when using other constructs like — when you create a method variable inside a , the function will be bound to the instance that is currently in scope.

The following new functions have also been added to deal with methods:

Check the manual for details fo how these functions should be used.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *