Made with game maker

Made with game maker

Everything you need to start making games

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Let’s Make a Game

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

«It’s easy to pick up and start learning. With GameMaker, making games is not only simple, but also fun.»

«GameMaker’s systems were easy enough to approach as a novice and are now so second-nature to me that I’m comfortable tackling larger-scale problems that I wouldn’t have dreamt of four years ago.»

“Using GameMaker’s in-built tools let me understand the role they play in game development and gave me the foundations I needed to go on to recreate any of them for myself in larger contexts. It was the perfect stepping stone for me to go from knowing nothing to feeling like I am an experienced games programmer.”

«GameMaker basically taught me how to make games.»

«Everything I know about programming I learned thanks to GameMaker. It was my very first coding experience and I’m glad I stuck with it. The GameMaker community is also vast and there’s tons of content in forums and tutorials, which made the learning process a lot less scary.»

«Honestly, without GameMaker, I probably wouldn’t even have gotten to the hobby stage of game development. It gave me an approachable way to get into game dev and realise my ideas, that I otherwise couldn’t have.»

«GML is a lot easier to learn than other programming languages.»

Разработка простой игры в Game Maker. Эпизод 0. Первые строки

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

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

Я хотел бы рассказать об игровом движке Game Maker и разместить несколько публикаций, в которых мы напишем клон не сложной игры, например, Plants vs Zombies. Возможно, добавим поддержку геймпада и сделаем, например, Android-версию.

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

Вступление

Game Maker — это невероятно простой игровой движок, позволяющий создать игры для большого числа платформ — Windows, Mac OS X, Ubuntu, Android, iOS, Tizen, Windows Phone, Windows 8, PlayStation 3, PS 4, PS Vita, Xbox One и HTML 5. Есть поддержка SteamWorks. В случае успеха вашей игры, портирование на другую платформу сложной задачей не будет.

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

YoYoGames — компания, создавшая Game Maker, недавно была приобретена Playtech, что дает уверенность в том, что Game Maker продолжит развиваться. Анонсированный Game Maker 2.0 вероятно будет еще более дружественным и простом, а также логично предположить, что будет обладать еще большими возможностями. Как пишут в пресс-релизе, GM 2.0 — одна из причин покупки компании.

В этой статье я кратко расскажу о Game Maker и мы сделаем простой набросок будущего проекта.

Для кого этот движок и с какой целью его еще можно использовать?
Для всех. Цель — любая 2D игра. Однако для тех, для кого программирование не родная стихия, а так же для быстрого прототипирования и создания игры с минимальными усилиями для любого желающего делать игры и/или заработать на них, Game Maker подойдет идеально.

Плюсы Game Maker

— простое вхождение;
— знакомый всем по Java/C/C#… синтаксис;
— возможность легкой компиляции на разные платформы;
— активное сообщество, которое за многие годы уже решило много проблем и написало код за вас;
— стандартный функционал, благодаря которому не нужно самому писать большое количество кода;
— расширяемость через extension’ы;
— справка (F1) очень простая и удобная с отличными объяснениями и примерами.

Минусы Game Maker

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

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

Что такое спрайт в Game Maker?

Это изображение/анимация, которые используются в игре. Они обладают своей маской, формы и размеры которой можно менять. Маска — это область изображения, которая реагирует на события столкновения объектов (если этот спрайт присвоен какому-то объекту), кликов по нему. Можно задать точку отрисовки (Origin) — например, от центра, угла или любой другой точки.

Так же для спрайта можно можно задать Texture Group. Нужно для оптимизации отрисовки (например, незачем держать в памяти texture pages с изображениями, которые используются на экране меню, когда у нас сейчас игровой экран). Для каждой Texture Group можно задать платформу, на которой они будут действовать. Например, для Android можно иметь менее детальные изображения, чем для Windows 8 планшетов.

Что такое объект (object) в Game Maker?

Это описание некоторой сущности, обладающая своими методами (функциями). Каждый объект рисует себя сам (если не задано иное), реагирует на стандартные события — нажатия клавиши, клика по спрайту и т.д… По аналогии с ООП — это класс (class).

Что такое инстанс (instance) в Game Maker?

Если объект — это просто описание сущности, то инстанс — это экземпляр объекта, его реализация в самой игре. Создав инстанс вы даете ему жизнь и теперь все события, описание которых есть в объекте начнут реагировать.
По аналогии с ООП — это объект (object).

Первое, что необходимо сделать — создать новую комнату (на левой панели правый клик на Rooms — Create Room). Назовем её rm_game. Зададим размеры окна во вкладке Settings — Width — 800, Height — 480, Speed — 60. Т.е. игра у нас будет происходить в окне 800х480, fps будет не превышать и стремиться к 60 кадрам. Сохраняем, закрываем.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Теперь нам нужен первый юнит. Пусть это будет классическое стреляющее растение. Но перед этим нам желательно создать объект, который будет родительским для всех пользовательских юнитов (да, примерно тоже, что и наследование в ООП). Так можно избежать повторяющейся логики для всех юнитов, а также как вы увидите ниже, можно будет обращаться ко всем типам созданных во время игры «детям» этого объекта.

По принципу, аналогичному со спрайтами и комнатами, создаем пустой объект. Назовем его o_unit_parent и больше пока с ним ничего не делаем. Теперь создадим o_unit_shooter и в графе Parent выберем o_unit_parent. Зададим ему спрайт — spr_unit_shooter. Для этого воспользуемся кнопкой, которая находится под именем.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Называть спрайты, объекты, комнаты и т.д. можно как вам удобно, но для того, чтобы потом не путаться, лучше сразу называть вещи своими именами, например, спрайты с приставкой spr_, объекты obj_ или o_, скрипты — scr_ и т.д.

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

Спрайт можно задавать и программно, но в таком случае он не будет отображаться в превью Project Structure слева. Теперь добавим событие, которое будет срабатывать при создании инстанса объекта. В этом событии нужно задать начальную инициализацию переменных, если они имеются. Нажмем Add Event. Как видите Game Maker позволяет каждому объекту отлавливать большое число событий. Нас интересует — Create.

Как видите справа в контейнере Actions в нескольких вкладках есть огромное количество drag’n’drop элементов, с помощью которых в теории можно создать совершенно полноценную игру не написав ни строчки кода. Но это для извращенцев и вероятно в Game Maker 2.0 этот ненужный функционал наконец уберут.

Перейдем по вкладку Control перетащим или сделаем правый клик по иконке Execute code. Откроется текстовый редактор, в котором и можно размещать игровую логику.

Все, возвращаемся к объекту o_unit_shooter и создаем новое событие — Alarm 0. Код, который мы напишем в этом событии как раз и будет срабатывать когда запущенный счетчик, который мы создали в событии Create. В событии Alarm 0 мы и будем создавать «пули» (в оригинале — горох), которыми стреляет растение. Добавим такой код:

Разберем этот код.

Как вы помните, в оригинале можно расставлять растительность только в определенных ячейках. Чтобы визуально было понятно в каких пределах можно поставить растение, создадим фон и зальем им нашу комнату. Правой кнопкой по Backgrounds — Create Background — Load Background, выбираем нужную картинку, скажем, 64х64 пикселя, обзываем bg_grass. Переходим в нашу комнату (rm_game), вкладка Backgrounds, выбираем созданный секунду назад фон. Ставим галочки, если не стоят как на изображении.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Добавим этому событию такой код:

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

В первых четырех строках мы объявляем локальные переменные. background_get_width, background_get_height — встроенные функции, возвращающие width и height нашего фона. Как видите эти данные нам понадобятся для того, что бы просчитать iX и iY. iX и iY — это будут координаты, в которых мы создадим экземпляр объекта o_unit_shooter. mouse_x, mouse_y — встроенные в Game Maker глобальные переменные (т.е. те, к которым мы может обратиться из любого места), хранящие текущие координаты курсора мыши (пальца). Т.к. мы работаем в событии Global left released, в них хранятся последние координаты где пользователь отпустил левую кнопку мыши (отпустил палец). Математические операции, результат которых присваиваются переменным iX, iY нужны для просчета координат, в которых экземпляр объекта o_unit_shooter будет находится ровно по средине ячейки фона bg_grass. Т.е. помните, что в Plants Vs Zombies растение нельзя поставить где угодно, только в определенной точке, но при этом кликнуть-то можно где угодно и растение поставится как раз в нужном месте. Этим и занимается весь код выше.

exit — код, который обрывает выполнение события. Т.е. если в координатах iX, iY какой-то юнит уже есть, срабатывает exit и инстанс o_unit_shooter не создается, т.к. мы прерываем выполнение всего последующего кода. Это нам нужно, чтобы в одной ячейке не могло стоять 2 пользовательских юнита.

Что ж, пришло время добавить первого врага. Создаем новый объект и опять же создадим базовый родительский объект. Назовем o_enemy_zombie и o_enemy_parent, который будет ему родительским. Создадим спрайт spr_enemy_zombie, отцентрируем и присвоим его o_enemy_zombie.

По сколько свойством всех врагов является движение в сторону растений, то создадим в o_enemy_parent в событии Create этот код:

На самом деле к ней тоже можно обратиться из другого объекта, но в случае если вы обратитесь к ней из другого объекта в момент, когда событие, в котором она создана уже закончилось, это вызовет ошибку — знакомый всем null pointer, ибо из памяти она уже выгружена.

Если сам не нравятся функции hspeed, wspeed вы можете сами их реализовать изменяя значение x или y в событии Step. Эти функции просто делают это за вас.

HP — это еще одна переменная, в которой мы будем хранить количество очков жизни врагов. Этой переменной будет «владеть» каждый инстанс, но ведь максимальное количество очков жизни у разных типов врагов разные, т.е. нужно как-то переопределить/перезадать это значение. Либо можно задать всем врагам одинаковое количество жизней, скажем, 100 и ввести понятие defence от которой будет зависеть получаемый врагом урон, но сейчас нету смысла усложнять, верно? Так что обойдемся только одной переменной — HP.

Запомните, gml — язык, используемый в Game Maker регистрозависимый, HP, hP, Hp и hp — будут разными переменными.

canAttack — просто переменная, которой мы присваиваем значение true(истина). Пока просто напишем и забудем о ней.

Раз у нас значение HP у каждого врага будет разное, нужно как-то переопределить это значение. Это очень-очень просто. Переходим к объекту o_enemy_zombie, создаем реакцию на событие Create и пишем код:

Функция event_inherited(); и занимается наследованием. Т.е. теперь o_enemy_zombie выполнит код:

Который «импортирует» эта функция, а затем значение выполнится строка — HP = 20;
Т.е. по факту на конец события Create объект o_enemy_zombie будет иметь такие свойства:

Если же мы забудем о функции event_inherited(); или забудем объекту o_enemy_zombie указать родительский объект, враг двигаться не будет, при попытке обратиться к переменной cHspeed этого объекта появится ошибка.

Великолепно, если мы захотим создать еще один тип врага, в событии Create мы напишем тоже самое, изменив на нужно количество HP:

Раз у зомби есть очки жизни, они должны быть и у растения. Добавьте самостоятельно в событие Create объекта o_unit_parent код HP = 20; и строку event_inherited(); в событие Create объекта o_unit_shooter.

А вы знаете?

Если вам не нужно ничего переопределять и дописывать в событии Create, добавлять код event_inherited(); без другой логики в событие не нужно — за вас это сделаем сам Game Maker. Тоже касается любых других событий, не только Create.

Это очень интересный момент. other — это инстанс объекта, с которым в этот момент события происходит коллизия. Естественно, т.к. этот код находится в событии столкновения с экземпляром объекта o_enemy_zombie, то в other и будет только инстанс o_enemy_zombie.

Ничего страшного в нем нет почти все конструкции вам уже знакомы.
if (!isActive) exit; — если объект не активен, т.е., скажем, отдыхает/перезаряжается/делает замах, данное событие выполнятся не будет. В следующих двух строках мы получаем координаты центра ячейки, находящейся слева от той, на которой сейчас находится центр нашего instance(помним, что x — возвращает координаты Origin-точки, а она у нас выставлена как раз по центру спрайта). Дальше мы смотрим, находится ли по координатам (leftCellCenterX, y) пользовательский юнит. Если там что-то есть происходит последующая логика, но о ней через секунду, если же там ничего нет, мы присваиваем hspeed значение переменной cHspeed, которую мы, помните, создаем в событии Create. Вот тут она и пригодилась. Смысл за этим скрывается такой — если наш зомби остановился для того, чтобы атаковать и уничтожил растение, нужно чтобы он продолжил свой путь. Можно, конечно, не вводить переменную cHspeed, но тогда нужно будет вспомнить где вы задаете скорость движения, а это забывается.

Это в случае если на пути зомби ничего нет, теперь же возвращаемся к моменту, когда нам предстоит бой. Первые же строки оказываются очень интересными, с подвохом. Дело в том, что объявив локальную переменную frontEnemySprtWidth мы в инстансе frontEnemy присваиваем ей значение. Знакомые с программированием, скажут, но ведь в таком случае мы обращаемся к переменной frontEnemySprtWidth не нашего зомби, а к переменной с таким же именем, но инстанса frontEnemy. Так да не так, дело в том, что локальные переменные(объявленные через var) становятся видимыми внутри этого события везде, даже изнутри инстанса frontEnemy. Таким образом в коде ошибки нет, мы действительно обращаемся именно к той переменной, которая была объявлена локальной внутри зомби. Если вы не поняли этого момента поэкспериментируйте или прочтите справку, там все прекрасно объяснено, а мы идем дальше.
Мы присвоили frontEnemySprtWidth значение длины(width) спрайта юнита пользователя(растения), который находится на ячейку левее нашего зомби. Вы скажете, а зачем нам городить такую сложную для первого понимания конструкцию, если можно обойтись var frontEnemySprtWidth = sprite_get_width(spr_unit_shooter);. Ответ прост — это сейчас у нас одно растение и мы знаем к какому спрайту обратиться, но при добавлении новых типов юнитов(подсолнухи и т.д.), придется городить громоздкую конструкцию switch, чтобы узнать что же за объект впереди нас, а так довольно просто решается эта проблемка.

Дальше мы проверяем, если расстояние между крайней правой точкой пользовательского юнита и крайней левой точкой нашего зомби меньше 12 пикселей, то мы останавливаем нашего зомби, проверяем может ли наш зомби атаковать(проверяем значение ранее созданной в событии Create объекта o_enemy_parent переменной canAttack), продолжается выполняться код, в котором мы говорим, что атаковать теперь уже нельзя и что следующий раз это можно будет сделать через room_speed * 1.2 кадров(через 60*1.2) — это мы делаем в alarm[0](сами добавьте его в соответствующее событие(Alarm 0) объекта o_enemy_parent, где напишите код canAttack = true;). Если атаковать можно, отнимаем у инстанса растения 5 очков жизни и проверяем, живо ли оно еще, если нет — уничтожаем.

Ну вот и отлично враг готов — он двигается, атакует и продолжает движение, если уничтожил растение, но у него есть один недостаток — его не существует. Мы создали только описание нашего врага, теперь нужно же помещать зомби на игровое поле. Возвращаемся в событие Create объекта o_game. Добавим код
alarm[0] = room_speed; // generate enemies

Т.е. через 60 кадров сработает Alarm 0 и будет создан зомби, правильно? Нет. Мы же не создали логики для этого Alarm. А код тут тоже простой:

Все просто — мы не будем усложнять и просто каждые 3 секунды(60 кадра * 3) создаем инстанс o_enemy_zombie по координатам X: room_width + sprite_get_width(spr_enemy_zombie)/2 + 1 т.е. за ровно на один пиксель правее, чем граница экрана, т.е. зомби изначально видно не будет и Y — случайная ячейка. room_width и room_height, как вы уже поняли, это width и height нашей комнаты. Т.е. 800 и 480 соответственно.

Координаты можно любые. Теперь мы можете задать вопрос, а как Game Maker определит, что нужно запускать комнату rm_game или «а что если у нас будет много комнат, с какой Game Maker начнет?». Все как всегда просто — самая верхняя комната запускается первой(их порядок можно менять перетягивая мышкой). Сейчас она у нас одна потому сразу она же и запустится.

Теперь у нас должно получиться что-то такое:

На этом первый эпизод закончен. Поздравляю, мы сделали прототип игры. Осталось совсем немного — сделать из него полноценную игру, чем и займемся в следующих частях.

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

Как видите по уроку, в некоторых планах текущая версия Game Maker не идеальна, многое приходится держать в голове, зато в Game Maker проще делать все остальное. Небольшое неудобство стоит того.

В следующем эпизоде:

— /теория/ скрипты
— /теория/ отладка
— /практика/ юнит подсолнухи
— /практика/ мана(солнышки)
— /практика/ генерация врагов волнами
— /практика/ газонокосилки
— /практика/ новые юниты зомби и растений
— /теория + практика/ примитивный интерфейс

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

Hero’s Trail: Create Your Own Action-Adventure Game In 30 Minutes

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Overview

Hi there! In this tutorial we’ll use the Hero’s Trail template to create our own action-adventure game. We’ll add coins, a sword attack, and the ability to defeat enemies.

We’ll customize the project so you can truly make Hero’s Trail your own.

At the end, we’ll upload our game to GX.games so you can share it with your friends and the rest of the world!

Let’s start by creating the project!

Creating Your Project

We’ll use the Hero’s Trail template as a starting point for our game.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This will open your new project where you can modify the template and play it. To play the game you can click on the Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game makerRun button at the top, or press F5 on your keyboard:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This will open up your game, where you can hit “Play” and move around the level using the arrow keys:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This is the base project that we’ll build upon to create our own fully featured action-adventure game!

The GameMaker Window

Your project will open in GameMaker, which is divided into two sections:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

The Asset Browser is where you will create assets (such as objects, sprites, etc.) and the Workspace is where you will edit those assets to make them your own.

Let’s go ahead and start using assets!

Adding Coins

Currently, our level is empty besides some baddies hunting the hero down. Let’s give him something to loot!

We’re going to add coins to the game: you will be able to place coins in the level and pick them up as the player:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

We’ll create an object asset for the coin, which we can place in a level as many times as we want.

We’ll program collisions between the player object and the coin object, so when the player touches a coin, the coin disappears.

Let’s make the coin object!

We’ll start by adding a new Object asset:

Open the “Objects” group in your Asset Browser and select the “Game” group within it.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Click on the Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker“Create Asset” button at the top and double-click on “Object”.

(Alternatively, you can click on «Objects» once and then hit “Create”.)

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This will create a new Object asset inside your selected group, and open its Object Editor window in your workspace.

Change its name to obj_coin:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

The project already contains a coin sprite that we can use for this object. (If you want to import your own, go ahead!)

In the Object window, click where it says “No Sprite” to open the Asset Explorer.

Open “Sprites”, then “Items” and select spr_coin.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

We created a new object asset, and assigned a sprite asset to it, which is simply an image.

This way the coin sprite (spr_coin) will always appear on the coin object (obj_coin).

Placing Coins

Our coin object is ready! You can now open the first room (rm_level_1) and start placing coins.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Doing so will open the Room Editor, which has many layers for you to place different kinds of assets.

First of all, make sure that the “Instances” layer is selected:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker
This layer is where you place objects.

Now you can drag the coin object from the Asset Browser into the room! You can also hold Alt and place coins simply by clicking and holding (make sure that obj_coin is selected).

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

There is only one coin object.

But, we can place it many times into the room!

Each coin placed in the room is known as an «instance». From one object, you can create many instances.

Customization!

Craft the hero’s trail by placing coins and barrels in his path.
Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Collecting Coins

We want the player to collect a coin on touching it. To make this work, we’ll make use of Events and Actions.

Events are placed inside Objects. GameMaker decides when a certain event runs (once, or every frame, or when a key is pressed, etc.)

Actions are placed inside Events. Each action has a unique purpose and effect.

You can add actions inside an event, and when GameMaker runs that event, all actions inside it are executed. This is how you program your objects!

But what are Events and Actions?!

Let’s say you have a recipe for pancakes, with all the steps in a list.

In this case, your recipe is the event and these steps are the actions.

When you start following a recipe, you have to follow all steps inside it; only then the recipe is considered finished.

Similarly, when an event runs, all of the actions inside it are executed.

Let’s program our coin!

We’ll do the following to program our coins to be collectable:

Open obj_coin. If the Events window is closed, click on the “Events” button to open it:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Click on “Add Event”. This will open a list with all events (recipes) that you can add into your object.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Go under “Collision”. This opens an asset list and lets you select an object to “collide” with.

Navigate to “Objects”, then “Game” and here, select obj_player.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

When you have chosen your event, you will be asked to choose between GML Visual and GML Code:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Select GML Visual, and make sure to enable «Don’t ask again for this project«. Hit «OK«.

Doing this will add the event to your object and open it in a new window. This is where you can start creating your recipe, to tell GameMaker what should happen when the coin touches the player.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

The new event window will mostly be empty, except for the panel on the right: the Toolbox.

The Toolbox

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

The Toolbox will be your most important tool for programming objects. It contains all the actions that you can use, and allows you to search through them using the “Search. ” field at the top.

Destroying the Coin

We are inside a collision event with the obj_player object. This means that the event will run when the coin touches a player, and all actions inside it will run too.

When that happens, we want the coin to be removed from the room. We’ll do the following to achieve that:

In the Toolbox, search for the “Destroy Instance” action. Drag that action into the event.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Search for the “Do Effect” action and drag it into the event as well.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

The first action will destroy the coin instance, removing it from the room. The second action will create a particle effect for some eye candy.

For the “Do Effect” action, use the same settings as shown in the following image:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Make sure to enable the «Relative» checkboxes for X and Y, as that makes sure that the effect appears at the coin’s position.

You can select the “Do Effect” action and press F1, which will take you to its manual page. There you can read more information about its options in detail!

Run the game, and you will see that the player is now able to collect coins!

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Customization!

Change the effect that appears when you collect a coin, in obj_coin‘s collision event.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker
You can change the Size too!

GameMaker has many types of effects that you can use, some of which are shown below:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Increasing Coins Value

Although you can now collect coins, you will notice that the coin counter at the top does not change. This is because we are not actually changing the player’s coins variable.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

What’s a Variable?

Let’s go back to the pancake recipe.

At the top of the recipe page, let’s say you have written:

Throughout the recipe you will now remember how many bananas you have to add, just by reading that text!

If you are feeling more hungry for bananas today because you watched a documentary on cute monkeys, you can increase that count.

…and you now have two more bananas in your recipe!

In this case, ‘Bananas’ is a variable.

It essentially stores a value and can be changed. We can easily create and modify variables like these in our code, so we know exactly how much we have of something!

The ‘coins’ variable

Our player object already contains a variable called coins, which stores the amount of coins it has. We simply need to increase this value when a coin is collected.

We previously added a collision event in obj_coin, so it could collide with obj_player. Now, we’ll add a collision event in obj_player, so it can collide with obj_coin and increase its own coins value.

Open obj_player. In its “Events” window, add a collision event with obj_coin.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

In this event, add the “Assign Variable” action. This action is used to change the value of a variable.

(Refer to this section for instructions on adding actions from the Toolbox.)

Use the following settings for the “Assign Variable” action:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Here, we’re assigning 1 to the coins variable. However, this will not simply set the variable to 1, because we’ve enabled the “Relative” option. This means that the value of “coins” will increase by 1, hence adding one coin!

Run the game now, and you will notice that the coin counter actually goes up when you collect a coin!

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Our game now has coins that can be placed anywhere and collected by the player to increase their score!

Adding a Sword

Currently the player can’t attack at all, so we’ll make it able to swing a sword so it can defeat any enemies in the way!

We’ll create a new object that will show a sword slashing animation.

Whenever the player presses Space, this sword object will be displayed.

When an enemy touches this sword object, it will be defeated.

The project contains a sprite called spr_sword_attack. This is what will be displayed over the player when the Space key is pressed, creating an attack:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Let’s start by creating an object for this.

Open the “Objects” group, then select the «Game» group and create a new Object asset. Name this obj_sword_attack.

Set its sprite to spr_sword_attack. You can find this sprite in the “Sprites” group under «Player».

You can also drag it from the Asset Browser and drop it into the Sprite section of the Object:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Refer to this section for instructions on creating objects.

One-Time Instance

Instances, by default, exist permanently in a room until they are manually destroyed. For example, if you place a coin in the first level, it will remain there until the player touches it.

This sword object will be created by the player, but we don’t want it to keep existing. We want it to destroy itself when its animation ends. This ensures that after pressing space once, the sword also appears only once.

We’ll do the following to implement this behaviour:

In the new obj_sword_attack object, click on “Add Event”, go under “Other” and select “Animation End”.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This event runs when the instance’s animation has ended. When this happens, we want it to destroy itself.

Search for “Destroy Instance” in the Toolbox and drag it into the event.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Our sword object is now ready: whenever it’s created by another object, it will only play once and then destroy itself.

Swinging the Sword

Let’s now allow the player to swing this sword when they press Space. We’ll do the following to achieve this:

Tip: You can press CTRL + T (or CMD + T on macOS) to open the “Go To” menu. This allows you to write the name of an asset (e.g. obj_player) and quickly jump to it!

Go into obj_player.

Click on “Add Event”, go under “Key Pressed” and select “Space”.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Add the “Create Instance” action from the Toolbox. This action is used to create a new instance of an object.

Then, add the “Assign Variable” action. We’ll use this to change the horizontal scale of the sword (to make it face left or right based on the player).

Use the following settings for both actions:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Each instance has an ID, which can be used to access it and modify its properties. In the “Create Instance” action, we have the “Target” option which holds the variable name that will store the ID. Since we’ve enabled “Temp”, this variable will be temporary.

Temporary variables only exist for the current event. After the event ends, a temporary variable is removed from memory.

The X scale of an instance controls its horizontal size, and it’s stored in the image_xscale variable. This variable is used by the player to flip its horizontal sprite, so that it looks left or right depending on the input:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

This same scale will now also be applied to the sword, so it faces left or right depending on where the player is facing. To achieve this, we’re using the “Assign Variable” action to set sword.image_xscale equal to image_xscale.

This is the sword’s X scale. Its image_xscale variable is accessed using a dot («.«) through the sword variable, which stores the instance ID.

This is the player’s own X scale.

Run the game and you will now be able to swing the sword horizontally!

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Making the sword swing in all 4 directions is covered in another part as it’s a longer process.

Defeating Enemies

We’ll now let the player defeat enemies by hitting them with the sword. Let’s do the following:

In the Asset Browser, go into “Objects”, then “Game” and open “Enemies”.

This group contains an object called obj_enemy_parent. This is a “parent” object for all enemies (currently it has only one «child»: obj_baddie). Any events added to this object will automatically be applied to all enemies.

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Open obj_enemy_parent and add a collision event with obj_sword_attack. This will run when the enemy touches the player’s sword (you know what’s going to happen then!).

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

In this event, add a “Destroy Instance” action and a “Do Effect” action. These are the same actions we used in obj_coin to destroy it on colliding with the player!

Since we have used these actions recently, you should be able to find them in the «Recently Used» section of the Toolbox, so you don’t have to search for them again.

Use the following settings for these actions:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Customization!

You can change the «Type» used in «Do Effect«, to create a different type of effect when an enemy is defeated.

You can even place multiple Do Effect actions to create various effects at the same time! Go ahead, give it a go.

When an enemy comes in contact with the sword, it will now destroy itself and create a particle effect. Even though we have not added this event into obj_baddie, it will still apply to it because it’s a child of obj_enemy_parent:

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

A child object does whatever its parent does.

Run the game and you will now be able to defeat enemies by swinging your sword! We’ve got some real power now!

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Optional Customization: RARE Coin!

GameMaker is based around objects, and to add new functionality to your game you simply make new objects and add/edit events!

For example: Create a second, rarer coin! Select obj_coin and hit CTRL+D to duplicate it (or do it through the right-click menu).

Name this new object obj_coin_rare.
Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker
In its Create event, change its colour to red so it looks different!
Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker
In obj_player, add a collision event with your new object, so when you touch the rare coin, you get 5 coins (or any other amount you like!):
Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker
Now place it in your level and reward your player for exploring!
Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

It will look red in the game only, not in the Room Editor, as it requires its Create event to be run for the colour to change.

You have now created your own action-adventure game and have customized it in your own way!

Now follow the next part, or continue reading the bonus part below to publish your game to GX.games so you can share your creation with your friends and family.

Publish to GX.games

Publish your game to GX.games for free, and share your creation with your friends and family.

Summary

We created our own game from Hero’s Trail, by adding a coins functionality and allowing the player to attack baddies. Here is a summary of what we’ve learned:

ВСЕ ЧТО НУЖНО, ЧТОБЫ СОЗДАТЬ ИГРУ

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

СДЕЛАЕМ ИГРУ

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

«GameMaker’s systems were easy enough to approach as a novice and are now so second-nature to me that I’m comfortable tackling larger-scale problems that I wouldn’t have dreamt of four years ago.»

“Using GameMaker’s in-built tools let me understand the role they play in game development and gave me the foundations I needed to go on to recreate any of them for myself in larger contexts. It was the perfect stepping stone for me to go from knowing nothing to feeling like I am an experienced games programmer.”

«GameMaker basically taught me how to make games.»

«Everything I know about programming I learned thanks to GameMaker. It was my very first coding experience and I’m glad I stuck with it. The GameMaker community is also vast and there’s tons of content in forums and tutorials, which made the learning process a lot less scary.»

«Honestly, without GameMaker, I probably wouldn’t even have gotten to the hobby stage of game development. It gave me an approachable way to get into game dev and realise my ideas, that I otherwise couldn’t have.»

Made with game maker

Made with game maker. Смотреть фото Made with game maker. Смотреть картинку Made with game maker. Картинка про Made with game maker. Фото Made with game maker

Efforts to make the gaming industry more inclusive are gaining traction across the games industry. But fostering inclusivity within the industry is only half the battle. There’s also a critical need to consider the talent pipeline: how can we better inspire, educate, and equip girls and young women to seek out careers in this space?

As the world’s largest mobile gaming destination, and with a mission to build products for everyone, Google Play set out to understand where and how this gender discrepancy starts.

Key Learning

TEEN GIRLS AND BOYS BOTH LOVE TO PLAY GAMES, BUT GIRLS ARE SIGNIFICANTLY LESS LIKELY TO MAKE THEM

We learned that the discrepancy between genders grows as teens move from playing to making games. Although girls make up one-third of teens interested in a career in game creation, the industry itself is less than one-quarter female. As we dug deeper, we found that these discrepancies are due to a host of structural and cultural factors.

Though they play at nearly the same rate as boys, girls are less likely to be interested in making games for a living, and even less likely to be employed in the gaming industry as adults.

Teens

Teens

interested in making games

Adults

in the games industry

Our Findings

1. First things first: Teen girls love to play

Despite the perception that video games are a male-dominated space, teen girls are avid game-players who have been playing for years. Games were their first introduction to personal technology. Even before they had mobile devices of their own, they were already playing on their parents’ phones and tablets.

The teen girls we met are sophisticated players. They see games as an important tool with the ability to help them learn, boost their mood, and engage with friends. The games they play are deeply integrated into their social lives, and serve as an outlet for competition, a topic of conversation, and a way to stay connected to friends throughout the day.

Playing games also sparks their imaginations. They inspire the imagination, even outside of play. 55% of teen girls who play say they’ve had an idea for a game before, and our conversations revealed creative concepts: a story game about a lost girl finding her way home; an RPG celebrating Valentine’s Day; an arcade multiplayer version of Pac-Man, and more.

Источники информации:

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

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