ГамеМэкиры – Создаем меню и загрузочный экран вместе с Ванакием



учится хорошо на ошибках а еще лучше на чужих сегодня урок по construct 2 но совсем в необычном формате поэтому смотрите оценивайте и конечно же запоминайте а меня по-прежнему зовут бармалей поехали на этот раз уроке я буду вести не один а точнее его буду вести вовсе не я а я в ноги и ванна кий у пластичный металл серебристо-серого цвета есть в этом в этом уроке я вместе с ван акен научу тебя создавать игровое меню а также загрузочный экран начнем и так вот справа где а то у нас написано про джексону информация вот ну в общем то вот ну по курсоров видите вот монахи хотел сказать что для того чтобы создать новый уровень который будет являться самим меню нужно обратить внимание на вкладку project расположенную в правом верхнем углу ну а что же дальше или нажимаем это дэвид и нажимаем it even щит и также до что это получать мы создали 2 как бы вторую сцену это сама сцена не говорю это уровень там центр вообще все мне что-то может меню быть загрузка сама игра что угодно по да что ты черт побери такое вещах ну давайте для удобства мы назовем их потому что так будет удобней и об щекам как бы действительно всегда старайтесь называть лайалл ты листы событие просто объекты это отличная привычка которая не раз сэкономит вам время так у нас тут сцена она по размеру сама как как сцена она у нас большим давайте она будет такая у нас там как какие в воле они . мы бы шаиш в анапе хотел сказать что неплохо было бы уменьшить размер уровня на котором находится меню для того чтобы подогнать размеры окна потому что в меню нам не нужно менять положение камеры она всегда должна стоять по центру для удобного взаимодействия с кнопками значит тут какую балку вы украшаете us вы даете спрайты разные текстуры здесь ставили как хотите украшаете все это сделаете на данном этапе создания как предложил ванадий нам нужно добавить все объекты которые будут являться элементами нашего меню а это такие объекты как во первых кнопки создать который можно как с помощью отдельного объекта с одноименным названием так и с помощью любого другого объекта например обычного спрайта во вторых нам нужен стиль оформление нашего меню я советую вам создать большую часть оформления в отдельном графическом редакторе а позже украсть его каким-нибудь частицами или эффектами в самом контракт но не нужно загружать уровень куча и спрайтов и текстов а я сделаю сипап рот прочь к вы будет чёрный фон типа вот такой в принципе можно не известно стоит дословно вы удалили последний экземпляр объекта спрайт 7 удаление последнего экземпляра и удаляет его из проекта чтобы полностью его удалить воспользуйтесь панелью project вроде все просто даже сам конструктор информируют вас об этом но многие продолжают допускать эту ошибку повторюсь для того чтобы удалить ненужный вам объект перейдите во вкладку project и сделайте это там иначе вы удалите объект лишь со сцены и при экспорте он никуда не денется есть такие текстуры где можно ставить the white background tylt что бегай ground ну что так он будет у меня монотонно поэтому будет нормально как бы выглядеть это все и при этом нормально на дне гарри нормально не совсем удачный пример демонстрации возможности tylt background поэтому напомню данный объект нужно использовать в том случае если вам нужно разместить множество однотипных объектов на сцене а если вы хотите чтобы ваш фон был одноцветным просто укажите нужный вам цвет в настройках слоя создадим буквы детям какие мыть вот текст типа название нашей игры светает ставлю вот жирный нежирный размер на самом деле как я уже говорил лучше делать это в отдельном графическом редакторе и загружать как спрайт ладно чем можно еще сделать блины не знаю ребят о частичке разные есть у нас и он делает вот разлить кишки идут о частичке сейчас вон наки покажет вам как делать не следует типа это давайте будет границу чтоб я знал где они находятся в общем как-то ракете а вот смотрите как это у меня выглядит я просто так вот их пара оставлял везде и вот выходит такие частички тип большое количество объектов по тикал на уровне сильно влияет на производительность поэтому используйте их с умом они пара оставлял везде и вот выходит такие частички тип ладно теперь нам надо сделать кнопочку на которой типа если мы нажимаем там начинается сама игра можем сделать спрайт свою текстуру и такая подсыпать ему сейчас я сделаю вот типа вот те создал спрайт такой зелененький мне прямоугольник будет но побольше можно его фсб и клонирую не нужно клонировать объекты для того чтобы создать элементы одного и того же типа для этого лучше используйте кадры анимации например мы создаем две кнопки добавляем один объект добавляем ему же еще один кадр анимации не забудем поставить скорость анимации на ноль для того чтобы кадры не менялись теперь в параметрах этих объектов укажем нужные кадры а уже в вершит при добавлении действия нашим объектам сравним значение текущих кадров анимации на основе которых и будет выполняться действия то есть если мы нажимаем на объект кнопка его кадр анимации равен нулю то мы начинаем игру а если его кадр анимации равен единице то мы выходим из игры это проще чем кажется и кстати самое самое главное а сейчас навострите ушки но запоминать не советую нам выход из игры принципе не нужен действительно зачем выход мы ведь тигру запускаем чтобы поиграть они чтобы по выходить но потому что мы играем как бы мы делаем игру для контрактов и рого получается что он для андроидов и браузеров но если мы в браузере нажмем exit то есть выйти что кладка закроется не да это нужно для классического и слив в классическом то там есть одна функция типа можно выключить приложение ну я и так сейчас поставлю потом еще покажу кое-что на самом деле возможность сделать выход в construct 2 имеется но из-за того что игры созданный на нем основаны на технологии html5 делается это через объект браузер но мы продолжаем плавно переходя к созданию событий значит добавляем события типа мышкой он обжиг клик выбираем объект сам у меня спросим ну и один раз хочу и систем что что систем короче год лет и тут мы в кавычках обязательно в кавычках пишем название уровня все есть еда это действительно все что требуется для создания кнопки новая игра вот вам и создания меню этот урок можно было уместить в две минуты но видимо вована kia что-то пошло не так и теперь возникает такой вопрос а как же сделать так ну а теперь ванна кию какого-то лешего приспичило показать как сделать дополнительную попоболь потенциальным игрокам вашей игры вот мы нажимаем на не game как сделать так чтобы было загрузка они сразу игра но сейчас мы это с левой значит он решает создать загрузочный экран но не для того чтобы скрасить секунду или минуты ожидания старта игры а для того чтобы увеличить саму время ожидания давайте посмотрим что же вытворяет этот в анапе я создаю повальную переменную как как ба ба ба ба ба ванную переменную типа будет называться на вот и тут мы выбираем сколько там будет секунд диктовать у меня будет длится 5 секунд это загрузка и теперь cd событие евреек секанс то есть каждую секунду так по стандарту по госту наверное с эту выбираем нашу переменную лаут по одному значение поскольку по одному и изначально у нас на нуле должна быть а.н. если рада если равно 0 way же игру из равно 5 то есть пять секунд тут муку тут мы уже пишем сколько хотим секунд пять допустим the system gold то есть заходит на уровень 1 моем случае вот как-то так сейчас название этого текста как он текст 5 давайте имена всем объектам и при этом эвристик то есть всегда у нас текст 5 то есть текст отображается такой какой и на глобальные переменные голод и при этом что что больше ничего во-первых рассмотрим самый распространенный просчет при создании события иврите а во-вторых я расскажу как создать настоящий загрузочный экран который будет использоваться вместо стандартного начнем с иврите как вы можете видеть его nike создал события которое каждую секунду прибавляет глобальной переменной лот одно значение следом он добавляет события которое так как не является триггером то есть выполняется много раз каждый тег проверяет равна ли переменной a lot 5 а дальше он вешает сюда еще иврите которая каждый тег выводит значение переменной лот на экран посредством объекта текст а следовательно каждый тег еще раз проверяется значение переменной лот теперь вопрос зачем проверять значение глобальной переменной лот дважды еще и каждый тег а минимальный тег я напомню это нуль целых шестнадцать тысячных секунды поэтому каждый раз при создании подобной группы событий в мире грустит один процессор задумайтесь ну а правильным решением в этом случае будет перемещение действия сад текст в первое событие и перемещение 2 события под 1 таким образом все эти события будут выполняться он раз в секунду теперь вкратце о том как создать свой загрузочный экран все что нам нужно сделать это создать новый уровень далее перейти в настройки проекта и изменить там два параметра первые это юз loader layout то есть использовать загрузочный экран далее выбрать этот загрузочный экран в поле выше first play all то есть первый уровень и будет нашим загрузочным экранам теперь нам осталось лишь добавить сюда события систем он лаут финиш то есть когда загрузка завершена действия систем год layout и выбираем нужный нам уровень обратно в кавычках будь то меню или же сама игра разумеется на этот загрузочный экран вы можете добавить различные объекты сделать прогресс бар и тому подобное кстати в создании прогресс бара или же просто подсчёта прогресса загрузки вам поможет выражение laughing прогресс вот такой вот экспресс урок все есть вот но на этом я закончу урок там уже если у вас есть свои когда своя фантазия так как бы извлечь какая игра у вас уже сами там работаете над этим и все ну что ж раз в анапе закончил то закончим и мы надеюсь вам понравился данный урок и новый формат если это действительно так то поддержи меня поставив лайк и подписавшись на канал до встречи пока [музыка]

FAQ Collision mask, image point ▌Construct 2



всем привет в этом видео я отвечу на один из самых часто задаваемых вопросов почему мой персонаж дергается проваливается сквозь текстуры меняет анимации на ходу и тому подобное поехали kill факел обычно причиной этой проблемы кроется в таких вещах как колледжем mask и матч пойнт origin или же ваши кривые руки с последним помочь никак не могу а вот с двумя первыми мы сейчас разберемся начнем с теории колледжем mask иначе маска соприкосновений нужно нам для того чтобы определить грани которые будут физически взаимодействовать с другими такими же гранями у других объектов допустим у нас есть два физических ящика один стоит на месте а другой падает на первые сверху вниз и что мы видим второй ящик приземлился на первые приземлился и не проваливается а всё почему потому что оба этих ящика имеют маски соприкосновений и выглядят они вот так [музыка] а теперь давайте изменим маску 2 ящика на вот такую и посмотрим что произойдет думаю этого достаточно чтобы понять что есть маска соприкосновений ну а теперь немного об ее использование в construct 2 существует три вида возможных масок это 2 дефолтной маски баулин бокс и circle то есть четырехугольник и круг и полигональная маска еще ее называют костанай то есть настраиваемой первые две нужны для создания типичных физических объектов таких как соответственно четырехугольник и круг а вторая для создания сложных много полигональных объектов и касательно использования этих масок есть несколько наставлений во-первых использовать полигональную маску с вот таким видом и использовать маску баулин бокс это не одно и то же казалось бы обе маски представляют из себя четырехугольники но есть тут один секрет первом случае коллизии то есть грани про считаются более простым а значит менее ресурса затратным для системы способом это обычное сравнение координат ширины и высоты объекта а во втором случае коллизии просчитывается в отдельном цикле для каждой грани исходя из этого также вытекает пару правил предостережение при использовании полигональной маски идеально использовать минимум граней то есть от трех до пяти и еще терпимо будет использование 8 граней но вот 15 плюс это уже перебор который вызовет сильное снижение производительности так что учитывайте это ну а теперь вернемся к основному вопросу и представим вот такую ситуацию исправить персонажи с двумя кадрами анимации а у этих кадров разные маски соприкосновений за ци-клим анимацию скорость смены кадров установим на 3 для наглядности а теперь запускаем отладчик и видим что во время того как кадр анимации меняется на 1 спрайт начинает проваливаться но наверняка у кого то из вас возникнет вопрос я ведь не трогал маску вообще первый раз и мне слышу почему она у меня не правильная дело в том что при добавлении объектов проект извне маска задается ему самостоятельно не забывайте об этом ну а теперь перейдём ко второй возможной причине неадекватного поведения ваших объектов image and origin сама маечку and origin это . которая определяет центр вашего спрайта то есть эта точка относительно которой будет перемещаться ваш объект а теперь представим ситуацию опять наш sprays двумя кадрами анимации но теперь с маской соприкосновений у него все нормально а вот и моих point origin по первого кадра стоит по центру а у второго где-то сбоку кстати для того чтобы удобно управлять имеешь поинтами можете воспользоваться нам подам например чтобы поставить и матч поинт в самый центр изображения нужно нажать клавишу нам 5 итак запускаем превью и видим что что то не так думаю из этого вам понятно что положение имидж по in the origin повторюсь еще раз определяющего ключевую в большинстве случаев центральную точку должно быть одинаковым у каждого кадра анимации ну и напоследок следует отметить что причиной дергано во поведения вашего анимированного объекта может быть банально разные размеры кадров анимации но думаю об этом вы и сами догадываетесь а на этом все понравилось видео ставь лайк и подписывайся на канал так как там тебя ждет еще куча новых видео до встречи [музыка]

Construct 2 ▌Раннер ▌Меню, Параллакс, Эффекты



привет сегодня мы заканчиваем основной цикл уроков по созданию простого раннеров construct 2 и в этом уроке мы создадим меню сделаем искусственный параллакс а также немного поработаем с эффектами слоя начнем [музыка] для начала рассмотрим все том что не рассмотрели в предыдущих уроках во первых это объекты заднего фона это обычные спрайты которые входят в одну семью и так как камера в игре не двигается параллакс с помощью слоев мы сделать не можем поэтому эти спрайты имеют поведение war суть его в том что по достижению конца уровня спрайт перемещается в его начало и так бесконечно следующая группа объектов это элементы интерфейса меню а также три копии объекта текст с разными значениями приватная переменная тип все эти объекты по умолчанию невидимы и находятся на другом слое для того чтобы мы могли добавить эффекты на первый слой не затронув меню а эффекты будут такие radial blur и grayscale по умолчанию интенсивность уберем на 0 чтобы они активировались только после смерти персонажа и для того чтобы это реализовать давайте перейдем в вершит и в событии при котором персонаж умирает добавим два действия первое систем ctr эффект параметр слой 0 эффект grayscale индекс параметра это его номер который считается сверху вниз и начинается с 0 данном случае яндекс 0 то есть это параметр интенсивность зададим ему значение 100 копируем и то же действие и меняем эффектно рейган был яндекс уже меняем на единицу и значение по-прежнему на 100 теперь после смерти будут применяться оба эти эффекты на базовый слой и теперь прежде чем активировать кнопки меню и заставить текст отображать набранные очки и рекорд мы сделаем искусственный параллакс для этого перейдем к событию в котором каждый тег меняют свое положение по x препятствия и добавим сюда такие действия облака сет excel . x минус 1 холмы сид xlv . x минус 2 горы суффикс -2 деревья стелс x минус 3 и кусты сэл x минус 4 тем самым облака будут двигаться медленнее всех горы и холмы немного быстрее деревья еще быстрее и кусты быстрее всех что и обеспечит нам эффект параллакса с этим мы разобрались теперь последнее что нам остается сделать это меню для этого перейдем события при котором персонаж уничтожается и добавим сюда такое действие меню family and visible весы был то есть делаем видимым наше меню а теперь добавим новое событие если семья меню видимо is visible и добавляем сюда под события если переменная тип текста равна единице то есть этот текст отображающий надпись points to этот текст становится видимым теперь копируем это событие два раза и меняем значение переменной тип на если тип равен двум и если тип равен трем если двум то это текст отображающий количество набранных очков за этот забег поэтому помимо того что мы делаем его видимым сделаем так чтобы он отображал набранные очки для этого добавим действия текст сет текст глобальная переменная ско ну и последний тип текста 3 он должен отображать рекорд поэтому создаем такое действие текст сет текст и пишем в кавычках best ставим амперсанд для того чтобы разделить текст и выражение и пишем сюда название глобальной переменной отвечающий за рекорд best score а теперь давайте активируем кнопки restart и выход для этого добавляем в и то же действие под события touch он точит обжиг объект кнопка перезагрузки то есть если мы прикасаемся к кнопке перезагрузка the browser will out ну если же мы прикасаемся кнопки закрытия the browser клаус ну и последнее что нам осталось сделать это отключить всевозможные движения объектов после уничтожения игрока а также остановить подсчет очков для этого во первых в этом событии добавим такие действия пила все тратит speed поставим на 0 то есть пила прекращает вращаться ну и колесо секса in active in active то есть колесов перестает качаться теперь поднимемся выше по событиям и найдем то при котором двигаются препятствия и background и сюда добавим условия если семья меню disable и инвертируем его то есть действие этого события будут выполняться только в том случае если меню невидимо а соответственно если персонаж не погиб точно такое же условие добавим и в события подсчета очков но на этом создание простого runner она construct 2 окончена исходник вы как всегда можете найти по ссылке в описании в моей группе вконтакте а также напомню вам что текстуры для создания товара мира я взял на сайте крафт пикс . нет предварительно оформив подписку чего и вам советую ссылка будет в описании но если вдруг тебе понравилась это видео то поставь лайк а так же подпишись на канал потому что в будущем на нем тебя ждет у моря разнообразных видео надеюсь еще увидимся до встречи

Creating a game in Construct 2 from scratch: part 7



hi everyone we are back for another installment of working on this barbarian game and construct 2 and this video is going to be a little different I already made several changes and I'm actually just going to review them with Korey here to show him what I did and at least a little bit going to how I made those particular changes in why so say hi Cory yeah how's it gone alright so first thing that you might notice that's different I am still sharing screen right yeah it looks like I am mm-hmm okay so I just added a text thing here to the HUD layer that I can drag down when I need to so I can do debugging I just add a line of code let's see if it still exists it's having the text yeah so you can see here set text to whatever okay yeah and that just in this case I was working on the camera stuff so that's one of the first things I changed which is not very noticeable unless you're comparing the previous video directly to what you're about to see but all right so now you can see the text that I just dragged on that's showing me the Y position of the camera uh-huh oh and there's new sound effects that you cannot hear Cory but everyone else should be able to alright and it's a little harder because I have enemies coming from the left and the right now which is another thing I added but anyway I also while I was tweaking the camera all it does is better protect the ability for the screen to shake I've made the screen shake more consistent universally no matter what no matter how high the character is on the screen and then I was able to make the screen shake a little less subtle and so I was using the the textures keep track of exactly where the Y position of the camera hands up they have any given circumstance so okay yeah looks like you've also got the the air Bosch working on the yes men so yes that's right yeah I can bash them in the face now that's one of the things I want to talk to you about as far as gameplay some ideas I have hate him no – dismissed Harry mom okay so one thing that is going to be cool remember how you created the second variation of a getting hit frame for the Birdman mm-hmm I'm gonna make it so when you bash him with the air bash move he's going to display that animation instead of the standard hit and he's going to side slide back more and farther and while he's sliding back that way he can actually bump Birdman that are behind him hmm so though you can get a chain reaction thing going and similarly we're going to be probably in the very next video adding the first powerup you can get and what I'm going to do is that's going to be the the fire variant and before I I had this idea of a general fire powerup which is kind of what you would expect in any kind of game or you get power-ups like a magical power-ups you you expect the kind of elemental ones like electricity and a fire and stuff but I also had this idea of what was going to be a different one which was an explosive force uh I would make them blow up but I realized I could potentially merge the fire one and the explosive force into the same thing and make it so that when you're doing the regular slash it emits a little like fire trail and but when you do the Vash that's what it would imbue the enemy you hit with fiery energy and the enemy that's going flying it'll have unique frames that make it look like it's like red and pulsing with fiery energy and that will blow up when it hits the ground and in a bigger explosion animation that also interned the explosion itself if that hits an enemy it will do the chain reaction thing that's the plan yeah yes anyway oh the other thing I was thinking of doing was making are you yep well I was gonna say I put any of these magical sort of I guess there would be gauntlets you know something like that mm-hmm do you think we would have anything like changing the range of his attacks or anything with those or that's what I was thinking yeah definitely and we just will just get to keep playing with the distance that each one comes out until it just feels the best for the gameplay so that we can make each one very different from each other but I was definitely picturing a fire one like the standard attack blur coming out quite a bit farther then obviously looking quite different so definitely and then I'm even considering adding it depends on how I work out the controls but for example I could do sort of a Castlevania style thing where holding up and then pressing the attack will throw a fireball if you have the firepower that would be very cool so there would be like the regular slash the bash slash which is down in attack and then a very long range attack that maybe would be the weakest of those attacks but would cover a much longer distance longer range attack so I just need to figure out because I do want to offer a a control scheme for this particular game that actually matches or that works with a one button controller and that matches the what is that game black belt the name was so generic I couldn't remember a black belt on the Sega Master System that was the original inspiration for this gameplay design our audience yeah exactly we're up his jump and and then you have an attack button although in black belt there were two buttons one worse were punch any other was for kick but we don't really this guy's not much of a kicker so I'm going to try to see if I can figure out how to make make it comfortable and easy to get out all of the moves in the black belt sort of style and with only one button so that would be a problem with up and attack being how you get out the fireball move because up would be jump in that case yes oh but I'll give that some thought I'm sure there's I'm sure there's a way to do it and I just have to figure it out but anyway yeah so the I also did some people may have noticed I slowed down the player movement I sped up the speed of the extreme foreground bushes and tree layer and I slowed down his general movement I also slowed down the gravity and the jump inertia and stuff a little bit this was specifically to make it match the actual amiga a most version right now but then we can we can tweak we can speed up the amiga version if we decide that's better or slow like I just slowed this one down I don't think I want it any slower than this but it does give me more than that already good pace yeah and the environment it moves in such a way to add the excitement but it's not overbearing right now it's but I think it just is because it's that thin strip as opposed if it was a really chaotic foreground it might it might be too distracting or something yeah right yeah yeah yeah I think it works great so that's one of the things I did and one of the other really important things I did is I finally fixed the really bad input bug that I want to explain what was happening let's see player input so the most important thing originally in these and I just fixed it for keyboard input as well even though I've been using an actual xbox controllers I'll explain it in the controller events but it's the same exact thing in keyboard events right here when someone is pressing to the right or to the originally if you recall I was just adding to left/right input we're subtracting one from left/right input and what I didn't realize is amazingly enough during gameplay it's actually possible at least with this xbox controller it was actually possible for me within less than one cycle one game loop of the logic I could actually switch from holding to the left or the right so that as far as it was concerned there was never a zero state there was there was never a state where I was neither holding left or right it was instantaneously first I was holding left and then the very next loop of the code I was holding right so even though I would think because you can't hold left and right at the same time right I would have thought you know certainly it would be slower than a 60th of a second that there would be at least one loop cycle where it would be at a zero state so that's what was causing all those failed attempts and so anyway so what I needed to do what I realized was happening because of that is if you can imagine I was I kept adding to or subtracting to this left or right but let's say I've been holding to the right already for several seconds so that left right input number might be way up to like a hundred or a million or a thousand or whatever and then when I start holding to the left instead of it going to zero and then starting to subtract immediately what it's doing is it's still at positive million and then it starts subtracting one so it's going to stay a negative number for a long time so the characters not going to turn around until minus one minus one minus one per every loop finally brings it all the way back down to a negative number instead of that positive number all right so that's what was happening so what I did was I changed the code to set left or right input two and then a maximum of these two possibilities which is left to right input plus one which is what it used to be and one to left to right but it has to be at least one so as soon as you're holding to the right it's got to be at least one or a left/right input plus one does that make sense so it just guarantees that it can't possibly stay a negative number once you start holding to the right and it's the same exact thing when you start holding to the left and makes sure now we're doing minimum so it has to be at most oh look at that it's still not perfect I have one here and this should actually be negative one catch that so let me fix that it was still good enough that it made my character like at worst case scenario it would have stuck on one and then the very next loop cycle it would have been 0 and then negative one and that would have been so fast that I wouldn't notice my character is not turning around it would have still been quite responsive to loop cycles is at most probably like a thirtieth of a second right on this PC so but it still is a bug technically so I want to clean that up while I'm here so that's this one here and this should be negative one so that was the biggest cause of the problem I did also in the gameplay events add to something as well which I did do a comment for all right here's the controller input fix let's see oh I see yeah there are two versions now that's what it is you see this one here if he's not on the floor okay and he's in the punch but you're holding left or right before if you jumped up in the air and you punched you would stop moving to the left or right you wouldn't be able to move continue moving to the left or right if you had punched so you suddenly your inertia would come to a dead stop where obviously if you're jumping forward and holding forward and you throw a punch you should keep going you should rally that inertia over so this fixed that stiffness that weirdness where if you jumped in the air you would not and that's because stuck in move because usually what you do is you check for stuck in moves so where I was so here it is up here stuck in zero left and right input so this won't work because if you're punching then stuck in move equals one right so this takes care of everything for when you're on the ground and when you're in the air and not punching and this takes care of if you're in the air and punching you should still be able to carry your inertia by continuing to hold left and right so the controls are much better now and boy does that make a difference ie I fail a lot less at hitting the bats with the bash which makes the game drastically more fun yep so that was some of the big code changes the other thing I already mentioned in passing was I added the goner for Birdman going to the coming from the left so all that was was cloning this the right sprite flipping the image naming it Birdman's blonde or left and then I just placed a few of those so now the game level is quite difficult oh there's another thing I did I have this spriter sprayer animation hoping for it I separated you had mentioned this and it was definitely good advice I separated the attack tell animation okay from the actual attack so the actual attack immediately starts with the attack frame and then does its fade out with the blur and then the tell is just that one tell frame to give the player a chance to get in there and get off his shorter range attack before the Birdman can attack him what's cool is this has a half a second timing built into it however so once I altered the code in here so we can see here these are the events that control the Birdman so I rearranged it a little so I said if the Birdman is walking or idle and he's a within tak range this one guarantees if he's within his own attack range limit minus 20 so he's quite close to the player then he's guaranteed to attack right remember that problem before sometimes he'd walk right through the player having never attacked so this guarantees once he gets to an even smaller distance from his maximum attack range you know within that 20 pixel range then he's going to definitely attack but we still have this one here where if he's within the attack range but not that close to the player then it's going to randomize that this is very similar to the original event we had that every tenth of a second if his attack likelihood is if a random number up to 10 is lower than or equal to that number that frequency variable we created for the Birdman then he'll attack so and then what we did was you'll see instead of playing the attack animation which was called punch instead he plays punched L so then we needed this event that says when punched L is finished then go to punch which is the actual sword swing and then we oh yeah the other thing I did which was so you see here when I when we go to punched L we set the playback speed ratio of the animation we just set to 0.6 which is a little more than half technically that would be twice the speed I think so it does start being a little less than half the speed but then I'm also adding random up to another little more than half the speed or 60% of the speed so it'll at least be 60% of the speed or it could be honored and 20% of the speed so you've got this little range difference of how long he'll stay in the attack tell animation before word attacks just so there's this tiny bit of randomness to how long he waits before he attacks in the actual hotel so that's what that does and then so yep so presently is there ever a time when they are actually like idling or not walking not yet but I was going to add that because the other thing I added so let's see and then the important thing is I think the way the spider plugin works is once you set a playback speed ratio it's not for the specific animation I think it sets it for everything from then on and until you return the playback speed ratio to the normal speed which is 1.0 so you'll see it says on animation punched l finished set playback speed ratio to 1 and in fact what I really should do is also add it because it is possible he'll never finish the punch til he might get attacked out of it and then all of his animations I should say will be slightly off in their timing they'll be either almost half speed or 100 and up to 120 % speed so I need to add another event that basically says I'll just copy and paste this and delete this stuff and we will copy this so his current animation punch sample and we're going to invert this so now if his animation that's playing right now is not punched at all it'll guarantee the animation speed goes back to the standard full speed alright so let me save that and then what else should I do oh yes somewhere I think it's called mirror for spider objects here oh it's somewhere I have it now we're the bird man okay so if he's walking or idle and the bird man is to the left of the player hmm then we swap his angle of movement and the mirroring to make him face the player so this makes the bird man always turn so long as he's not stuck mid swing or if he's stuck in the getting hit sequence or he stuck swinging or doing the swing tail then he'll in those circumstances he can't just turn around instantaneously but as soon as he's not stuck in the middle of something he'll turn around to face the player or walk toward the player so if you manage to jump over them or you were invulnerable and you walked through them to the other side they will turn around at their nearest chance to do so so that's another thing I added alright I just remembered another thing that I had done and that is originally we had a problem with the bird men when they were spawned each of them was at a slightly different y-coordinate there was nothing making sure that they were perfectly at ground level and you could see I was sloppy with the placement so you could see this one here is a lot higher I can make a rectangular shape so we could see that he's good for worse or more pixels to high and they're just they're not all carefully placed but I also don't want us to have to be that careful when we're placing these so what I did is I simply added to the on start of layout uncertainly out here it is I have a sub event now or two sub events that for each of the Birdman spawner sprites it goes through each one of them that's what the for each loop does we set its Y to the exact position of the top of the floor collide so the floor collide is hidden now but the point is that there is I'll just do this see that red sprite there or actually it's a tiled background object so the bounding box top is the exact top pixel coordinate there so on any level no matter where that is if we've placed these ground enemy spawner things then it's going to immediately put them all exactly on top of the ground because if you look at the actual anchor point it's at the exact bottom so it's going to align the exact bottom with the exact top of that ground which is also how it works for the player Center player because he does have the platform behavior and because that is there you could put you could start to level with him up here but he's just going to fall and land perfectly on the ground so this just ensures all of the bird people are on the same exact ground level as well and then one thing that I did want to do quickly that I haven't done yet if you don't mind what I want to do is finally add the code since we have the art in that makes these buttons change and darken and look depressed when you and I don't mean sad I mean press down when when you actually hold an input on the keyboard or a controller everything looks like that so let me go into the event sheet let's see should I add this I think I will add this to the player input stuff so I'll just make it group I'll be a little organized this time add group and we'll call this update buttons will do yeah that's fine we're going to compare a variable which is going to be left to right input is greater than zero that's good then that's going to the right so we need the I didn't rename that to down apparently but the right button we want to set the animation to pressed that's what the animation is called the artwork in it and then we can just copy paste that and we could actually invert that so if it's not greater than zero then we could change it back to defaults and I'm just gonna really quickly run the game to make sure that it's working make sure of my logic right before I do the same for all the other buttons there we go so I have the obviously the little anchor point a tiny bit misaligned I think it seems to be shifting position in a way it shouldn't but the logic works so I'll just worry about that part for now and get it working for all the buttons and then I can tweak the coordinates later on so I'm gonna vent sheep their input so now I can just copy and paste that and change this to B that's the same will do less than zero and we'll edit this to less than zero and we're going to we're gonna replace the object and we're replacing it with the left button okay that's it for that cut up and paste this again and now you're going to do will do the UP button so in place objects and we're going to do the UP button and now we need to change this variable to up-down unless then is indeed up and then change this up down okay that's good so now we'll do the down button so replace that object where is it there replace object and down button which is currently called left button three he'll fix that in a minute and so now up-down has to be greater than zero so it's already yep it's already down so it gets super depressed that is true so then we need to change these to place object hey I thought I just did this oh not yet I did I just got fooled because it's called left button silly me so now all right yeah let me go back here and fix this to be down button all right and now we just need to do the B and a for now as well oops your input so now we are going to do face object and we are going to do all to the B button first and change this to be v1 for button one greater than zero be home and I already replace that so that should be fine Oh actually should that should be one be the a button button one is a that's a good question that will soon see I wasn't yeah I was not quite sure yeah I had that set up me neither b2 b2 and oh yeah okay place the object and we need be but presumably oh no I did a I did B button first saw a button so I might need to reverse these but oh no no second here so up down left right that's all working very well yep no that's good well it's good in a sense that's the way they're lined up on an Xbox controller I think this is an Xbox one controller I'm not sure anymore no this one is a 360 but so the bellick's button is labeled a that's on the left and this is labeled B oh yeah I have those backwards yeah yeah just yeah we've got a what kind of putting B on top of a but not you not the other on so yeah okay all right let's sloppiness there so what we're gonna need to decide we might need to reverse the labels BNA because at least most PC owners will be going with the Xbox controller variants so a tends to be on the left and be on the right eye so yeah I guess I'll switch it does that make sense what about yeah yeah I mean it I guess it doesn't matter that much but yeah for for the consistency of the Xbox would definitely make sense ok so now that I've done that yeah they did that weird thing where they labeled them like sort of like the Nintendo buttons but they switched them around or whatever like so it's not exactly the same alright so let's see if I have the pressed day there it is right there there we go maybe that will fix the offset issue in this particular one – I don't think it I just cropped them differently like like a noob okay that's alright good enough for now I just want to get it functioning and then I'll clean it up when it's not recording because that's just lazy we're not lazy but it's just kind of boring work of tweaking the position of the hot spot or recrop in the images to make them cropped exactly the same mm-hm otherwise that was good but now I need to switch the logic right for those buttons clear input so I think I need to do this now let's see if I am correct so now they should be properly labeled a and B a B yep okay now it matches the Xbox controller and the button that I expect to be jumped the button on the left still jumps all right that's good all right all working I just need to tweak their images at a later point it was relatively painless we even fixed some little oversight issues but anyway so getting back on point there was a very important bug that Corey had noticed that we I will demonstrate right now and that is currently when the bird men are on screen they always attack at the exact same time the even the ones so it's back to the synchronized dancing thing so that should not be happening so I need to take a look at the gameplay events and I can use this search to narrow it down because I know it's the event that has punch tell in it so here it is so here's the logic for it so let's take a look this checks what animation it's playing so that should narrow it down at least to Bergman that specifically are either playing walk or idle but that does not narrow it down completely but then we have these other sub events that then check some calculations comparing variables and doing some math so obviously the problem is because we're doing these fancy math checks here in this code it's lost track of which particular bird man that that we're talking about so it's affecting all of them so what I should be able to do is I'm going to add add an event that simply does another for each that seems to be the topic of this video for each object so for each bird man and I'm going to just grab this entire of and here that controls the Birdman and I'm going to make it a sub event of that so now this should in theory make it definitely only try each Birdman one of the time through the loop cycle and so so during that one loop of logic it's going to say okay let me check all of these things for one Birdman at a time go through them all and only affect the Birdman that that match all of these criteria basically so let's see if that fixed it let's get those Birdman on the screen cue music all right excellent nice okay so now they are all attacking when they actually should be and as a dance troupe that is absolutely working great some good progress there okay so the last thing I wanted to mention what I'm thinking of doing to sort of adding more of that risk versus reward gameplay right now the heart appears very frequently and it's just on a random generator so what I'm thinking of doing is having a nice effect and adding a few things to the UI I'm thinking of basically two kinds of energy one that would be like health energy and one that would be like attack energy or magic energy in general so the idea would be that you're filling up so every enemy like let's say the flying enemy every flying enemy you destroy will release one kind of energy and it'll just be like a magic glowing shape or glittery thing or whatever right and it'll just appear for a second after the enemy is done exploding and then it'll fly up to that part of the hod up there and it'll like that pod will glow for a second and then fill up a little more does that make sense mm-hmm and then every time it fills up completely then like if it's the health type energy once that fills up then the whole thing will appear will fly across the screen at least within a certain amount of time maybe with some little amount of randomizing you know what I mean like you no one is coming soon because you filled that up and then so it would be one for one for attack energy and the other for the different power up you're going to get in that given level like the fire power or whatever the other different powers that we end up giving to the player so that plays on the idea we had discussed that idea several videos back that there's this guy that's helping you mm-hm and like he's up basically a wizard or alchemist or something and he's the one that either gave you the gauntlets or explained to you how to use the gauntlets or something and so we can make him say like you need to collect a certain amount of this energies for me to be able to conjure this thing and send it your way all right and then there's the two different kinds of energy so that's what I'm thinking of doing to make it cleave and we can still make it so occasionally randomly he might or at specific parts of level like maybe regardless of what you've generated or if you have not generated enough yet maybe sometimes he's also trying to build up or collect that kind of energy himself so sometimes maybe it it will be more random or in specific places like it will give you something special uh-huh but otherwise I kind of like the idea of you're sort of earning your way to it which will encourage people to not just try to dodge every enemy and keep running forward right that right they'll feel the need to to destroy more of the enemies and maybe we'll do like a multiplier bonus where you like if you bash enemies into others and stuff like that maybe it'll make more of that energy appear out of the destroyed enemies or something like that huh so that's the plan for the next video is to before the next video I'll probably tweak these pressed button image anchor points or hotspots so that they stay in the exact right place when they are pressed but then in the next video like before then I'll have done the art required for the fire powerup and will actually add all that logic in and get that game play working for the fire power right right so there's I just remembered one more thing I started doing I realized what we can do is consolidate these objects which I already started doing but did not finish and that is you see how I renamed the bat to bashed enemy huh and now he has different animations he has the bat version and the Falcon animation and he'll also have like flaming bat flaming Falcon whatever ice bat ice Falcon all that kind of stuff whatever powers we give like the different bash variants uh-huh and we could do the same thing for the flying bat so we flying enemy so we have bet in Falcon so that's going to make it much easier for me to do that thing I wanted to where I had Universal code right because now I can just create variables that say like if you get hit switch to this animation but instead of just naming a very specific animation I can use a variable that would be like so what I'm going to do is I'm going to add I'm not going to do this during this video I'm just explaining ahead but in here so now these will be the spawners for any walking enemy from left or right and there's going to be a value in here that's going to say bird or bat or whatever and then the in the code there's going to be a variant of the code that says if the variable is set to bird then create bird right and then so what it's going to do is it's going to or I shouldn't be saying that for the bird man but for the flying enemies for sure all it's doing is creating the same sprite which is just flying enemy but it's going to say change the animation to match that exact string so for example I would just go in here and add the instance variable so you can see we're already able to set the speed of each generated thing so we're just going to add another thing which will be a text variable and it'll just say which enemy and for example this would be bird or did I call it bird or Falcon I think I called it Falcon Falcon is back Falcon there we go so it's going to say just create that general thing and then change its animation to and then the value which enemy so in other layouts it'll just be which enemy will set it to bat or whatever whatever the final obvious for that and then same thing like when this is hit it's going to know and in fact I'm going to pass that variable along so let's just do that right now and so in this flying enemy we're going to also give it a text variable that will also be called with enemy so we're going to be passing this string value along from the spawner to the actual thing just so it knows what kind of an enemy its it is as well so this will be Falcon by default and then so when when it gets hit by the player bash and it creates just a general bashed enemy then it's going to know which animation to switch it to as well which is the same exact name which you can see is bet or Falcon oh so that way it's nice and tidy we're not going to need different sprites for each one it's just going to be and that way we can have the universal code for any vast any type of bash flying an immediate heading into any kind of ground-based enemy yeah so I just got the groundwork started for that so that's another thing that I'll probably do just because it's a lot of kind of boring work I'll probably do some of that off video too but that that's another thing I have in the works to further tidy up the code a bit but that's that's about all I had in mind for this particular video did you have any thoughts are thing or things you'd like to see oh I guess I should also design and get that hot to art ready for the two different energy types yeah my one thing I was going to mention about that with the HUD is it does look like we may have to I don't know play with the spacing a bit because it looks like there's not much space there to put that run it might get a little crammed in the middle yeah I was thinking about moving this over a few pixels this way yeah in this over a few pixels this way perhaps and I was thinking vertical bars that you fill up so they can actually be quite small like two different colored vertical bars so you don't need a lot of space but it'll look a little weird if there's two there and they're not perfectly centered yeah so I do feel like I need to move these over a little bit and maybe buy those from here yeah regarding had you know you've got the sort of gauntlet like things on the button right do are those gonna serve a purpose later on or they are purely there right now just to add some graphical element to the HUD some kind of quote unquote framing but in just sort of a visual theme but they that was definitely just kind of placeholder art to put something there and start to get a feeling for the style though I wondered I mean you said you were gonna have to kind of small meters I wonder if like right you can we could do something with those two side gallons to make them those actual things you know yeah that's a great idea because not only could we do that we can make these get brighter and brighter instead of bars that fill up right right and so we could just change this art and then the other thing we could do potentially to further consolidate communication is have the actual Gauntlet images change depending on what powerup you get what type of gauntlet yeah and eventually I do plan on let's see I don't have that folder open at the moment but I plan on it creating character maps in the spriter file that actually Julie represent the different gauntlet types you can get so your character will actually change even his idol and just even when he's not attacking he'll look different will have different looking gauntlets on his arm still have like cool red orange gauntlets when he's in the fire mode and stuff like that yeah so that'll be pretty cool too so he can and I'm thinking of making it so that when you grab the powerup that changes what kind of like basically transforms your gauntlets he'll like paws in the air so since he'll always be jumping up in the air to grab it like even do that you know how it does the tiny paws right now when you do the bash thing I'm thinking of doing the same time paws but maybe changing the color tinting of the entire background which would be a simple palette change on the Amiga and then having a cool animation where he goes into like a pose like facing forward on the screen with a cool like powering up pose and then like half the gauntlets change right and maybe do a cool voice sample or something yeah power up I have the power and that's right but yeah that's the plan so that that's gonna be the cool stuff that I want to get done or at least mostly get done in the next video is and by that point we're gonna have something very closely approaching at least seemingly feature complete level the only thing we would need to do at that point is make it so that at the end of the level you can actually exit the level and it would go to the next screen but obviously in the final version we're going to have bosses and sub bosses on a given level so eventually we'll add that that code that's going to make it where we can designate where a specific boss or sub bosses and then create basically a screen anchor that says when you get to this point stop the scrolling and don't let the player scroll anywhere past this point until that enemy is destroyed right and then the scrolling will wake back up basically did they do that I mean I know they I thought they did that in black belt right where yeah yeah it would sort of go along until it was like a sort of setting scene and then guys would just still keep coming in on that one screen or something like yeah I remember exactly it would certainly like that in the bosses where the scrolling would would would stop when you're dealing with some bosses on the level you know I think even but I don't remember I've not played the game in years I really should play it again since we're working on this just in case I get reminded of something to do or not do I'm but there's I'm pretty sure it does I think like like Mario we're or that I should say the first Super Mario Brothers game where you scroll from left to right and then you can't go back at any more like it only Scrolls in one direction right yeah so I'm thinking of doing the same thing to some extent maybe or at least in some portions where once you get to a certain point almost like checkpoints then you can't scroll back anymore which I'm their real amiga version will help with memory because we could potentially like while you're fighting the boss it could be loading in new graphics and dumping graphics you don't need any more yeah because I mean it seems like you're gonna be progressing the one direction I don't know if they would ever really be a reason for you to have to go back in row ever or if so only a very short distance to chase down an enemy you really wanted to kill because you need like the energy type or something like that in general there's not a lot of needs so I'm thinking of at least doing the checkpoint thing where then the scrolling gets stopped or I may just make it like you can scroll back a maximum of for one screen with once you go any distance you can only back up a little bit I mean so something like that would probably work fine then which it'll just make it easier one that people won't waste time going back and forth on a level they don't need to especially since in this game when an enemy disappears off screen they're just gone like there's no point for them to exist anymore so it's not like Double Dragon or something where you need to defeat certain enemies to progress further in the game other than bosses obviously yeah that's that's what I have in mind for next time so otherwise I think there was something else you had asked me that like we weren't recording I can't know it was oh yeah it was with regards to the buttons like a and B which one was jump or attack yeah I was assuming at some point we're gonna have like some sort of configuration where you can smoke so there will definitely be a setting screen where you can customise your input and probably choose like even on keyboard choose any keys that'll work for either of the buttons or at the very least to reverse the jump and attack buttons right to make sure because I know that drives me nuts when I'm used to that certain button configurations which one is jump which one is a tack and when they're quote unquote backwards as far as I'm concerned sub-grant we're going to make sure that any player that's used to any button configuration will be able to switch them how they like it so yeah that will definitely make that a feature it's not too hard to do so anyway that's that should be about it for this video thanks everyone for watching

Construct 2 – Creating a Basic Node.js WS WebSocket Server and Client



hello everybody and welcome to a construct 2 tutorial on how to use nodejs and the WS WebSockets library in order to create a server that you can connect to using construct 2 and the WebSocket plugin that is provided by serie now what we're gonna have to do first is we're gonna have to download it install nodejs it's kind of an of course sort of thing so let's save that and run it so boom let's go ahead and get this alright so we're gonna just kind of install this really no reason to change anything in particular we can just let it go about its business so we get a wait till it's done and it is finished woohoo yeah there was much rejoicing alright so next what we need to do is we need to get the Tobias WebSocket library so let's go ahead and we're gonna copy this from the front page this is github.com slash WebSockets /ws I'll be putting both links in the description so you don't have to worry about that and on a side note this is for this tutorial is pretty much just for windows only just because construct 2 is a windows only software currently so yeah yeah yeah as I flip my hands around alright so what we're gonna do is we're going to use this little line and this goes into our command line so what we're gonna do now first what we need to do actually sorry before this once we have this open we actually need to create a nice shiny little folder for our project to reside or sorry for the server to reside and so we're gonna create a new folder we're gonna call this test serve underscore or server use underscores not spaces that's generally good practice we're using command line commands anyway so we're gonna CD we're gonna do dot dot yep okay good I'm remembering my command line I know I could have gone to the top-level directory but oh alright so what we're gonna do is we're gonna go CD and then we're gonna do CD we're gonna do test server we're gonna go to a little test server and then what we're gonna do is we're gonna write paste and we can paste this little line of code so we're gonna we're gonna poop that and it should all of it should go just fine I believe I honestly don't know exactly what all of these are but so far as far as I know they are only of course they're only warnings not legitimate errors that will prevent us from using the library so we don't have to worry about this we are now done and so what we need to do is we need to create a J's file here now I personally like using brackets dot I brackets or bracket from brackets tayo a little and because this is a very nice code editor and it's built I believe mostly or primarily with web development in mind so it's got a nice little J's code editing think I'm losing losing my terminology as I go along anyway so what we're gonna do is Rex are going to create a new and this is my this is my other foot and this is the one project that I've been working on but so what we're going to do is we're gonna actually going to go back to the web site and we're just going to pretty much copy and paste the server example that they have because it's pretty much just all done for us and we don't I mean there's really we could just reuse all this code right here so what we're gonna do is we're gonna save actually we're going to save as because we need to get this directly inside of our test server folder so we're gonna call this test server why someone talking so loud in the background test server dot je s alright so once we've got all this in our nice little J's file what we're going to do is we're going to go over to construct two and now we need to start making a project that's actually going to be able to connect so we're gonna create just a little empty project and I'm gonna size down the layout size I don't know why the layout size is always that weirdo default that makes no sense but I don't really care too much right now so what we're gonna do is we're gonna insert an object now what we need is a little text box box but a text object that way we can record some of what are the responses from our server are so we're gonna do is were just going to size this out doesn't matter particular we can keep it twelve just to race the text and then what we're gonna do is we're gonna create a little button so we can have something to connect to and then disconnect wrong actually we don't really need a disconnect button because we're just creating a game artwork so you don't really need a disconnect button in this case we're not going to really get into that at the moment but this is just going to be a basic connection to so what we're gonna do here is we can just leave this as an OK button it doesn't particularly matter but um yeah now we need to make an event so when our button is clicked we rope sorry I almost forget this all the time until they go to actually add something but we need a new object and our object types we need the web socket so now we can actually add a web socket action to connect now what we're gonna be doing is we need to get neck to the localhost literally just this on port I think 8080 is the default that their example server uses now this is fine so I'll find and dandy when we're starting a server and we're also running the client on the server we're just gonna be entering localhost so for all intents and purposes as long as you're testing as long as you're running the client and hosting the server on the same machine you just use URL localhost and then whatever port that you have specified right here so it could be 8080 or it could be a host and host of all sorts of other Hort numbers that are available on your machine so we don't need a protocol we're just gonna click done and so once our button is there so what we're gonna do is now we are going to add a event so on opened when our WebSocket connection is opened what we need to do is we need to log this so we need to append text so what I usually do is just let's go with connection opened and then we do an N or sorry just an and newline and this is so we create another line which new text will be entered or sorry appended to in the text box if we have more text so then what we do is in the case of an error so on error just going to copy paste this down if you ctrl and drag you can drag a new copy into it and for some reason there's still a few glitches in the UI and and construct to that ad or that wind up duplicating the things that you're trying to copy and paste that's really odd because it's like selects more than one but that's side note this is fine so what we're gonna do is we're gonna just gonna say connection error that'll be good enough you can also log specific errors or at least the error details but we're just going to do this because this is this is fine for a basic project so then I believe this this should all be enough now what we need to do is we need to actually run our test server so what we're going to need to do is we are going to we're gonna create a new and we are need we basically we need a CMD file so in something that is going to invoke node to run our server so whatever the server name is we go do node space and then test underscore sir oops sorry test underscore server dot J yes I forgot the capital T why did I do that alright so this is good enough and we're gonna go back to our folder our test server folder and we're gonna call this run server server dot CMD boom all right so now it's here and we're just gonna do this all right and we can see it's running if it hasn't given us any errors we can also log just a line that says something like server started if we would like but that's another just sort of optional things when you're creating very basic connection trying to get this all set up so now what we're gonna do is we're gonna run layout and we're gonna press ok and connection opened and there we go we have successfully opened a connection to a WebSocket server using construct two and nodejs and the WS library so that's about it so we're done for now but there are many other things we can do as you can see I really sort of fleshed out a very basic server as well as a game loop on the server and some different key logging and such in the future I'll probably make a few more tutorials so you guys can get a sense for how to design something like a basic game that use it that interacts with the server and maybe and or maybe a login server and for that I would like to learn myself personally how to use MongoDB because that is a database software that also comes with a node.js driver so we can actually etch and save information such as players statistics username password and such and we can make it also a login server thank you very much for watching and I will see you guys all next time

Создай свою игру! 👾 Введение 🚀 Основы Construct 2



привет меня зовут кирилл в некоторых кругах также известен как бармалей уже 3 года я редко но занимаюсь созданием видео уроков посвященных разработке игр с помощью программы конструктора игр под названием scirra construct 2 но общий стаж работы в этой программе у меня составляет более 5 лет у меня есть канал на youtube где вы можете найти больше видео уроков и не только и группа вконтакте где я иногда отвечаю на вопросы связанные с contract думаю это все что вам нужно знать обо мне теперь поговорим о курсе которую вы в данный момент начинаете смотреть поделенным на 14 уроков в каждом из которых мы будем реализовывать часть проекта игры жанра платформер вплоть до экспорта о том что такое платформер и и экспорт я подробнее расскажу в следующих уроков сейчас хочу сказать что курс изначально создавался мной для совсем новичков то есть для тех людей которые никогда не сталкивались ни с программированием не с созданием игр именно поэтому конечный результат курса не будет являться полноценной игрой это скорее будет набор механик присущих именно жанру платформер с помощью которых вы я надеюсь изучите основы и втянитесь в этот безграничный мир создании игр ну а теперь поговорим о том месте в котором мы с вами будем творить чудеса то есть и конструкторы игр скира конспект 2 сильно углубляться в историю программа я не буду просто скажу что это такой конструктор игр который по задумке авторов призван сделать процесс создания игр более доступным с помощью такой штуки как визуально редактор кода на основе событий и действий то есть это значит что за весь курс мы с вами не напишем ни одной строчки кода звучит круто так оно и есть поэтому сейчас же предлагаю вам перейти к следующему уроку которому уже наконец начнем работу с этой программой [музыка]

A Beginner's Guide to Construct 3: 04 Player Character & Camera



hello and welcome my name is Matthew Marco and this is the fourth video in the beginner's guide to construct three and in this particular video I want to show you guys how you can create a player character that is functional as a platformer and a camera that will follow the player throughout the level because by default the camera does not follow players so we're going to cover all those things you need to know to just get that player ready to go and start working on your platformer alright so in this particular case I do want to mention right off the bat I should have said this in the last video but I'm going to say it in the beginning of this one keep in mind that if you're using other sprites other than the ones I'm using the ones I'm using a very small sprites and so they're working and you might bring in one of your sprites say you use the Kenny's free assets that I linked you to also if you're using those assets you'll notice they'll come in as ginormous okay that's all dependant on the initial side that we created the layout when we created our first scene and the size of the map now right now the size of the map which we can see over here the layout is 640 by 360 okay so that's pretty small okay and so you can kind of see right here this is what it looks like that box is where the whole layout is now if we want to make a really long platformer right we're going to increase the length of this a lot right so it's going to be a lot longer than 640 you know it might be four thousand five who knows like how long it goes out depending on what we need but just keep that in mind that's how you only change the size of the map you want to change the initial window you don't have to restart the whole thing again that would be silly you just want to go to in this case the project properties under the layout and click on View and then down here you're going to see this section right here the viewport size at 320 by 180 that was what we said initially you can change that number you can change the rendering box to be bigger so yes you can either scale down your sprites but if you just want to leave them one-to-one and want to worry about that right then you just want to make sure you increase the viewport size for the initial game size and of course increase the size of the entire level to match and so you can how you can change some of the other things here too like landscape and any others things that we were doing before so there's a lot of cool functions here you can even have a default background color splash color yada-yada-yada I'm not really going to get into that but that's that kind of stuff that you can add here so we'll click back on layout and let's get started actually creating the character themselves so creating the character is pretty simple we just double-click in the scene we're going to add a sprite right so we'll scroll down here and click on sprite click and add him we'll add them above the ground somewhere around here so we'll click like this go to load it up I already have the thing loaded up but under the assets the player folder and in this case idle that's what we're gonna start with we're just going to pick the first frame we're going to do animations in just a bit but we'll start off by doing this we have the character we zoom up bottom you see how real small he is right of course if you're using a larger one you'd see it bigger here but I can zoom up on him just hitting control in the mouse wheel all right cool but we'll get into this as I said before in just a moment what we want to do first though is make sure that a player character actually works right so that the collision on the ground is working everything's functional before we go too far ahead of ourselves so what we want to do is just add a behavior that's pretty simple right behaviors over here will click on behaviors add new behavior and cool thing about constructed automatically allows you to add different types of movement behaviors like things that function like turrets or a directional movement you know our a car movement so in this case we just want platformer and we're going to hit add okay now all you want to do of course from here is just test it out in order to test it out to make sure everything's working we're going to hit the play button right up here in the preview so we'll hit play the window in this case because the screen small is pretty small I'll just expand it out using this and there you go now if you use the arrow keys left and right well movie now this guy by default flying right and he jumps like ridiculously high like way out of the screen okay so you want to be mindful of that but the default functions are better suited for larger pixel sizes keep in mind once again I'm going to give you some numbers here we're going to fix these you can see that yeah he doesn't look the right way he's not animating and all that other crap but that's what we're about to do we're going to fix but as I said before the speed and all that other stuff that's all dependent on the sides of the sprite the size of your world and kind of how you want to design if you wanted to go flying on purpose well then design the map that way but in the beginning these are the numbers you got to tweak so I have them right here you see these are the numbers that I have set to make this size of a character and this world work good that's so I will reiterate it might not work for your so you play with these numbers now we'll talk a little bit about what the numbers mean so that you can change them around yourself let's take a look at the first one which is max of course that's pretty obvious how fast it goes in this case because it's a small pixel it's going way too fast okay so we're going to set it down to 120 slow them down a bit okay and then accelerates and decelerates you leave another cool thing goes and whenever you select anything over here in behaviors or properties I should say not just behaviors but all properties look down here you'll see right here it even explains you what the max speed is right saying how that works right how many pixels per second and yadda-yadda is going to travel and so these are all important things to pay attention to as you click you'll get different things down there so what we want to do also is what are we flying out of the world let's jump so I'm going to reduce his jump down to 350 ok gravity we're going to leave alone we're actually going to drop down the max fall to 500 okay and we're going to do double jump I find double jump fun you don't have to add double jump but you can jump sustained I'm going to leave at 0 but if you want basically it means if you hold down the jump button which is up on the keyboard if you hold that down the longer you hold it the higher you'll go and this isn't how many milliseconds until you know whatever it's it's definitely to see it set it right there so you can tweak these numbers for I wanted but this part pay a lot of attention to it get it just right right in the beginning don't move I've already tested this that's why I know my numbers are good but you want to make sure that you get your numbers good because as you to start designing a map and your numbers are off if you just tweak them a little bit like the jump just a little bit less a little bit more something you break your game right and so you really don't want to start building your map into you really get controls down ok so now if we hit play we'll be able to see that the character now moves and a little bit more realistic speed and he can jump and double jump and I got it set just perfectly so that he can double jump up there he can't jump normally but if you have to double jump he can get up there so it's pretty fun to do like I said I'm a big fan of double jump ok so here you go so once again still no animation still not looking right like if we hit left he doesn't need doesn't look left and all that stuff so those are some of the things that we're going to need to work on as next right so let's go and hit up animation so let me scroll down here and we'll talk about the animations so double click on the sprite whoops and you know I totally forgot to do this but make sure that you name it so name it player because this is important I actually have a lot of things based on the name right throughout the rest of the assignment so if you do not name your character player you will actually start typing in player whenever I say to do don't realize that those are connected it won't work so make sure you name them player so that works regardless of what it is okay so we've named them player you can rename them by you know clicking over here right clicking and hit rename or you can actually with the object selected name it up here so you do have a multiple ways to rename things okay so sorry I totally forgot to say that but whatever it's done now okay so now we want to double click on the player object to bring up again this animation editor that we talked about before and this is how the animations work now I have the in this case I have my origin point selected so that's why this is over here but if you had say something else selected you'll see different things but right here where it says animations let's rename this right so we're going to start with the first one I'm going to call it idle okay so this is going to be as idle animation so we'll name it idle and this is important once again that you name things the same way I named them so they work properly okay so we'll have idle here and what we want to do with this animation is add more frames so right now we only have that first frame we need the other frame so in this particular case the artist has four frames you're going to right-click and you can go import frames if you could do it from a strip so if you actually have like a texture strip or a character sheet or whatnot texture strip but a character sheet or a character strip you could do it that way but I have them as individual files or frames so that's how I'm going to select them so do foam files and I'll click the rest of them so two three and four and I'll hit open so now you should have all of his friends in order to test an animation you just right click on the animation go preview you'll see this little preview now you see that he stopped and he was kind of sliding so there's a couple things that we need to fix and a little slow so we need to fix that but you didn't restart and watch it again in yadda yadda but what we want to do and I already did the settings for you so if you're once again using the same stuff I'm using it's pretty simple we're going to do is we're going to set the speed here to eight so we're going to speed them up just a little bit and we do want to loop it right so that when they stay there's constantly in the idle animation so now I'll try that again we'll hit preview and there you go now the only thing that looks weird of course is that he goes scooting forward for a split second when he when he's in the second frame and we'll fix that in a moment I'll talk about that a little bit later but I want to first get all the other animations done because it's kind of important that I do that before I fix the frame you'll find out why in just a moment so let's do run next okay so we'll come in here we'll right-click in here and do add animation and we're going to rename it's right to run so we'll type in run okay and we'll want to make sure that in this case okay whoops I didn't want to do that so we want to make sure in this case we're going to come down here and add the frames for run so we'll do import frames from files so let's see if we can do this quickly so we'll go and grab run and there's ten frames of this one so ahead all ten you don't want the first frame it's empty so let's just select it hit delete and get rid of it and there we go there's our animation okay click on run and the numbers that I have set here is 14 for speed and loop yes otherwise it looks like he's going real slow so we don't want to make a real slow and this speed also is important like the speed of how fast you run the animation is also how fast the character moves so like in the game if he's not moving all that fast and there you go it looks pretty cool but if he's not moving all that fast in the game and his animations quick it looks silly or vice versa if he's moving super fast those animations slow look silly so you want to make sure that your speed is also dependent and matches the speed of the character in-game okay and like I said I've already worked a number so I know this works for mine but you'll have to tweak them yourselves all right so let's add jump okay so I'm going to right click in here and another animation right rename we're going to call this one jump cool thing about jump is literally just one frame so all you have to just come down here import frames from files we'll go find the jump right so the fall jump and whatever here's jump literally one frame hit open or that's fall sorry jump right here hit open delete the original frame cool click on it we're going to want we don't want it to loop so that's okay able to set the speed to zero time Technica doesn't really matter because really isn't an animation it's just a frame but whatever I'm going to do it anyways and then we'll do fall so let's do that one next and actually I know I call it falling and the other ones even though I say fall there so I will add the animation I'll call it fall Ling so let's do that there and we'll call it falling okay and we're right clicking here and once again do the same thing from files ok choose fall hit open delete the first frame all right once again click on this we don't want loop with this leave the speed to zero and we're good to go and then your last ones shooting now the shooting animation we're really not going to get to in a long time really videos 9 and 10 are on shooting so this one's going to be kind of hanging around for a while you know not being used but just know that we're going to just build all our animations now so I know let's call it shoot not shooting what it's called shoot but this way you know we have it done and we're ready to go to use the future okay and like I said there's a reason why we want all of our animations done anyways and we'll see that in a moment so let's go in here right click import frames from files I'm going to choose the shooting one now in this case it's called bow for this we're going to go 1 through 5 hit open once again delete this and good so now we have that guy in there we want the speed to be pretty quick so 15 and obviously we don't want it to loop okay because we're just going to hit the button while every time we hit the button he'll shoot as opposed to just constantly shooting if you have something where he's constantly shooting then I guess you can set it to loop but we're not doing that okay so there you go and obviously you can always check and preview your animations okay restart it soon all right cool so there we go so now the important thing is now that we have the animations right in order to get the character to work properly there's a couple important things one is this origin point which I had selected by default and two is collision okay so those are the things that I'm talking about down here that we got to make sure happens to the character so let's do collision first we'll kick in collision you'll see that collision is much larger than the character in a lot of these cases actually as big as the initial frame is so what I'm going to do is I'm going to click on these two hold ctrl and da just move them down so it's kind of like it's you know closing you can move you can see it slowly move remember these pixels are so big if you're someone in the middle of a pixel it won't change the number you see if I'm moving it up a little bit notice how my x and y values for these aren't changing because it's such a tiny thing if your image is really big then yes a couple of little movements might be changing the numbers but we're just going to get it so it kind of fits its head this is good enough right we don't need it to be absolutely perfect this long is really close this is we're dealing with literally just one pixel my brain if you really want you can slide them over one pixel but we can take a look at each of the animations you'll see in this animation he leans forward a little bit so we'll probably just leave it that way now it would take us freaking a century to go in here and change all of them at the same time that would be a little silly so what I'm going to do is I'm actually going to right click on the collision itself and we're actually going to do apply the whole animation or in this case if you want you apply to all animations just manipulate some the other ones so do apply to all animations and this is why I remember I told you to do all the animations first and now he should for every frame of every animation have the same collision now we will notice in some cases like this where he's running in his head pops up a little bit but whatever if his head goes through a piece of thing just a little bit like air goes through no big deal I mean I guess you can change it but I'm not a big fan of like constantly changing the collision and the size of the collision for the for the character because any all these weird things that happen during animations and swapping in animations and so on so we're going to keep that now the only one that might want to change in this particular cases are shooting animations those are a little odd with it with it being so far in front or behind the character but to be fair I'll just leave it because they don't think it real we really ruin anything in this case so we'll just set it that way and everything should be good as far as the collisions go okay now we need to do the origin point so click on orange point and those at the origin point by default is right in the middle of a space now the this matters for a couple reasons this is kind of where each the origin point is basically where each frame center is on so it does matter and remember with our idle animations what does anyone do that well you remember in our idle animation when it gets that little pop so we'll come in here well preview and has that little poppies flying forward that has to do with the fact that the the origin point isn't lined up the same way it is with the other images so what do I mean by that let's take a look we look at 0 2 & 3 notice origin point compared to his body is the same but if we go to 1 now all of a sudden knows how its bodies move forward in order to point is over here so this is all we really have to do to fix this animation is move this over 1 but we also don't want it to be in the middle of the character because there's a couple things that are going to be depending on the origin point being at the feet of the character such as the dust which we're going to do in a moment okay so let's move this over so on the origin point we come up here and right-click and we can do quick assign we're going to a quick assign to the bottom which will automatically assign it to the bottom middle which is where we want it and that's awesome for all of them all right so you can see right here that it obviously doesn't apply to all it's just that one but yes we can right-click on it and then do the same thing we did with the other ones apply to all animations and now every frame of every animation will have in the same spot now we're going to add another origin point later for the bow where the basically we want the arrow to spawn out from the character but we'll get to that later when we actually get to shooting but just be mindful of that we'll revisit this area then so let's fix the idle animation real quick and it's simple really just want to move this point over a little bit so you can either type in seven up here I can click forward remember since it's so small just make sure that seven just plus one whatever whatever yours is plus one and now if I hit play or preview right he should actually look a little funky there so let's try this okay six that's a little odd maybe because he's going fast let's check this out let's actually test them out in level first before we get too much in this so let me hit play and okay cool it was just the animation being funky in the editor as you can see here it looks nice and clean okay but remember even though we have the idle animation working and that looks cool he doesn't swap animations while moving and of course while jumping in anything he's just constantly stuck in idle okay and we don't want that right that's a little silly so that's where we finally get into in this case actually sorry I should say let's create the dust first I was gonna say we're going to get into the event sheet but we'll do that just right after we create the dust particle so the dust particle is a particle system that we're going to add that when he lands and you saw in the preview one here like when I did this one right here so when he lands in my preview boom see how the dust kind of comes up whereas fetus that's what we're about to create so let's do that real fast and switch back over to this okay so I'm going to add something new to the scene double click will type in particles okay and see right there as particles will edit we'll actually add it outside the scenes so it needs to be in the scene it's not the scene with the layout but not in the actual view okay that's important because we're going to have it spawn where the character is and not just be randomly shooting in the air or some so let's find the particle that this person I read it's called player dust honestly if you look at it you can make this in 10 seconds it's really just like a little Plus Ryan just looks like a + or across that's kind of you know like a dust color or whatever so cool that's the particle in there we're going to rename it right so remember we want to rename things and we're going to rename this one to dust okay so we know what it is I'm going to move it off screen a little bit and there we go so it's right there cool off the screen and now we're going to follow all the settings that we see over here another important thing is we do and I jumped a little bit ahead but we want to make sure sent to the top layer so we're going to right-click go to Z order and do top layer this is so that the dust appears in front of the character not like behind him looks a little weird if it's just coming there like the dust is only coming up behind them let's have it pop in front of them so it looks more like it's surrounding him makes a little more sense so that's what we're doing with that and now we're going to match these attributes and you'll see right here remember before as I said before if you click on this it'll tell you what it is so right in this case basically how many particles are shooting out per second we're going to reduce it way down to a we don't want 50 that's a little silly so we'll go in here spray cone so this is the direction right now it's going out this direction at a 60 degree angle we're gonna type in 180 so it shoots straight up okay we're going to also make it one shot okay so we select it here we're going to make this one shot sort of continuous spray so it only happens once oh I don't just keep going forever okay the speed of it want to slow it way down so let's go in and set that to 10 all right sighs we want them way smaller we don't want these things to be spawning giant so we'll do that we're leave opacity at 100 if you want to be like a little bit opaque I'm not a pig but a little bit transparent then you can drop that but we're just going to leave it I'm in a negative 10 for the grow rate so it shrinks over time instead of gets larger over time we're going to do eight in the X randomizer okay and these numbers might not work for like I said once again if your sizes are a little different you might find that you're gonna have to tweak these numbers but this is just as I said before for what I did and I had to tweak the numbers and figure it out until it worked right for me now here negative 10 and gravity and we're also going to set randomized speedrun either 0 or s is almost a zero we're not going to have it fader actors can timeout expire meaning that a certain time in this case it says one second we're going to change to a half a second it will disappear so and a half a second I do 0.5 now in point five seconds it will disappear okay so cool we've got it made and now we have to do all the important things to get the player to work so one last thing we got to add before we can actually get into the event sheet and start creating this stuff so yeah I mean I'm not going necessary in a logical order you might go why are we doing this now jump in here I'm just trying to save time if I just kept bouncing back and forth between things this video would be even longer than it's already going to be okay so let's quickly add a keyboard input to these scenes so if you ever want to do in the event sheet something that is assigned to a keyboard input or a mouse input which will do also a little bit later you want to add it to the scene so how do you do that you double click in here you come in and we'll just type in keyboard try our key and you'll see right there there's keyboard we'll add keyboard and right here at keyboards been added so that all needs to be is in the universe right in the object types we're not going to do anything else with it outside of that now we have everything created we have the animations the dust and the keyboard so we can make this entire player movement section inside of our event sheet so right now we have a empty event she we want to start off by doing is right clicking I'm going to add a group now a group actually counts as one of your events and remember we only have 50 events so you want to use these sparingly in fact this is the only group if you're trying to save and I'm going to imagine most of you are if you're going to try to save as many events as possible not player group one called player movement sorry I'm like typing while I'm thinking here okay so player movement and we'll hit OK and now it makes like almost like I said a group that you can dump everything into as you can see kind of in here alright and that's important because later when we go to do the shooting animation when the players in the air and they go to shoot they can't because these movements the player movement stuff is going to screw it up so we're going to basically shut off everything under player movement for a moment while he's shooting and then turn it back on when he's done shooting and that's going to help us so basically that's important for the future as far as that's concerned but every other time when you see in mine and go this one see I'll have these in categories they are like categories like categories against weak right categories right camera coins checkpoints and so on we're not going to want to add those because as you can see they're adding events so make sure that you just have them all listed it's not going to be as organized but it will save you on your events so just be mindful that if you have infinite events you have the full version or you have the unlimited educational than whatever just make the events and it's a little bit cleaner but this would be the only important one right so now let's actually add an event so click on here and so you'll see that everything that we've added to the scene already is existing into a event so what do we want to do to what in this case we want the player to do a bunch of things so here's the logic behind it right so obviously we want the player to play the right animations when we're doing certain things we want them to be mirrored when he looks the other direction right so if you go left you want to turn left and go right you want to go back right and we want the jump and fall animations to play at the right time and then also when he lands on the ground we want him to go back to idle animation and then have the dust come out so that's what all of this is it's basically what it's happening here so let's start by the top by choosing player so what we're saying is we want the player and this is how the logic of these vent sheets work but it basically says if the player is moving so let's just type in moving up here we don't have to like look for it it might take a little bit longer but player is moving and we're going to add another condition because you've got to be two things well right click on and hit add and then do another condition so if the player is moving and in this case the player is on the floor so we type in floor right so both these two things so this is where the understanding the logic of the coding comes in and I can actually move this down a little bit so we can see this a little bit better we're going to set the animation to run so we'll have add action so what we're going to do is set the player's animation and we'll do set animation and we'll type and run in between these quotations whoops will do run right there and from the beginning we don't need to do a different frame and had done and awesome so now if we hit play you'll see it work right so as soon as I start moving he'll start running really cool but notice how when I stop he's still running and that's the problem right once again logic we got to think like a programmer thing we're basically saying once you start running play run but there's no place where we basically say when he's not running don't stall or change it back to idle and so that's what we're going to need to do is think through all of that ok so this is where your programming logic is going to have to come into play all right so in the next case what we're going to do is we're going to get it so that he does do idle when he stops so let's do a new event add event do player ok we're going to choose player in this case we're going to make sure on stopped so let's start typing and stopped all right so one player on stopped okay and then we're going to add a condition because we want two things that he stopped and he's on the floor just like the other one because we don't want to be in the air and we're any stopped or whatever um and you're not pressing any directional button so well type in this um whoops let me try this again so let's click on this we'll do add condition so they want player and we'll type it floor I was typing in floor too early so come in here so when the player is stopped and on the floor have the player set animation play in this case idle so now we'll hit done if I hit play maximize that he runs when I stop he idles runs stop idles cool so we know that's working now let's get them to look the other way when he starts running the other way so let's start by adding another event in this case keyboard because it's important that we know which input we're pushing so we'll do keyboard and we're going to do on a key press not on key code press keep rest okay we're going to set the key to be in this particular case to be the left arrow okay so we're going to click left on our keyboard or the left arrow it will automatically update that and say say left arrow and okay and then we'll have done so basically when you press left what do you want to do now in this case we also want to have another condition we're going to add a condition in this condition is if the player isn't mirrored because right now he's not married he's just default so we'll just have player so when we press left and the player isn't mirror and we're going type in mirrored here you'll notice that you can only pick mirrored there is no not mirrored so just click the mirrored anyways and what you'll do is you'll right click on the is mirrored so whenever you see an X in here that means it's inverted so come in right click and go inverts and now it means is not mirrored so one player is not mirrored and you're pressing left what do you want to do well of course you want a mirror so we'll click on player ok and then what we'll do is we'll set mirrors so we'll just type in mirrored and boom set mirrored so now and you can choose not married but we'll do that in a moment when we go the other direction hit done so you press left here is in mirrored mirror now of course we don't want them stuck that way so we're going to do it so that the other way reverts that so add another one right another keyboard function on key pressed what do we want to click right arrow this time hit OK done and we're going to add a new in this case once again condition same thing but now player is mirrored instead of not mirrored so we'll leave it just mirrored cool so if he's pressing right and he's mirrored what do we want to do we want to make them not mirrors so we'll do player is not mirrored start typing in mirrored click on that set it to not married and we're good to go cool so now if I hit play maximized here if I hit left he goes left right goes right and so on right everything's looking good except for the jump and the dust I jump fallen dust so let's do those and we'll be done with our cool little animation section we can get to the smooth camera follow alright so let's do this real quick so once again at another event so we're going to add player so when player once again we want to do in this case we're going to do when player is jumping so we'll start typing jumping okay so it's jump you have another animation if you do double jump we're just going to do that we're going to make a little simpler here so when the player is jumping we're going to add an action so what do we want we want the player to play an animation so set animation and in this case would we call it jump so we're just going to add jump and we'll hit done alright awesome so that one's there now we can another one so another action or event so we'll do one player is falling right so is falling we'll click on that what happens well we play that following animation so player set animation and remember I called it falling even though I had to set fall on the other side so we'll type in falling is done and now we should be able to see that work properly so jump different animation fall right you see his hand changes as he goes down as hair moves a little bit different so we get both those really just the frame but it happened so quick it's hard to notice so that's good that's working lastly let's get the dust to work so once again and also we want to get it so that when he lands he goes back to idle because when he lands he might still be jumping or whatever because it's supposed to be when he's on the ground so if he's still running you might get this bug where he's still running in place when he land so we have to set it so that when the player lands so in this case on landed so we'll do on landed and start typing landed here so when the player lands what do we want to do well what we wanted to do is play the idle animation so player set animation set the idle come in here idle done and we want to spawn the dust and this is where the origin point is also important as I said before we want the dust to spawn at his feet so we're not going to click on dust don't be deceived we actually want to click on system and then go create object and now we can choose dust so what we want to create is the dust so we'll create the dust where do you want it what layer well there's only one layer right now so it's really irrelevant it's going to leave that if you have other layers then you would put that there but we don't we can actually pick a XY position in the world but that's silly we want it to be on the player so let's do a little right here as we start typing in player so we want to pick a player in this case dot X so the players X position and the player and you guessed it the players dot Y position ok and then hit done so now that should work so let's test it out boom boom look at that dust every time he lands awesome well boom right so really cool just adds that little extra flare if you're trying to polish up your stuff it's really that polished that kind of helps really sell your game and your creativity and your professionalism all right so very very less thing I know this videos getting extra long but we really need to put this all in one let's do the camera real quick it's not super hard but let's go and do that so now we're going to add the smooth follow camera so what we want to do is we want to create a small box right so we're going to make our own sprite okay so let's go back to the layout here I'm just going to right click insert object or double-click really doesn't matter click on sprite boom let's make our own object in this case I'm just going to take the Paint Bucket I'm going to make like a green block whatever okay so we don't need to actually have anything this is just the object that we can visually see that represents the camera so now that we've made this we'll just shut this off and of course we're going to want to call it camera so so we know what it is so camera all right there we go so we got our camera and see now obviously this block is giant so let's shrink it way down and that'll serve as our camera we can put it next to the character like I usually like to put it like right next because it's going to have to move to where the character is so put it close to him when he starts okay so we kind of moved it in there right and we want to make it invisible so the initial visibility so any object any sprite we don't want to see this green box going around this represents the camera we don't want to see it so we're going to come over here in properties and says initial initially visible no we're going to say no so I check that off and now you won't be able to see it so now we're going to add a behavior so come over to behaviors and what we wanted to do is edit behavior we're going to add a scroll to behavior so you can type in scroll right so the scroll too so we're going to choose scroll to right and so on basically at this point what do we want it to just click the scroll to all right well obviously we want to scroll to the player but we're going to have to do that in the coding so it has set to not coding with the event so we have a set to scroll to awesome one last thing we got to do is go into the events obviously if you're if you're not trying to save events you can make a new group right by right-clicking group so it's a little more organized but in this case we're going to save so I'm not going to do that for the moment but what we're going to do is we just add a knot to the player but just a new event outside of player movement it's going to be a system one okay so we're going to choose system we're going to type in every tick so this basically means every tick of the game every moment that's happening in the game right we click what we want is every tick what do we want happen every tick we want the camera right to set itself so what I'm going to do here is you can kind of see if I actually scroll this over so let me scroll this over here so we can see what's going on because it's kind of like a long set of code right here that we're going to have to add so this gets just a little bit more complex than what we've done before but just know that this is basically it's going to smooth follow so there's a little bit of like a you know a catch up speed for the camera doesn't immediately just perfectly follow them it's going to be like slowly following and you see what I mean in a moment alright so we'll have the camera we're going to do set position okay so you see there's things like set angle and stuff is already being set size set positions what we want so what do we want to do well in the X and the y we got to do this crazy stuff here so what we're going to do is we're going to type in lerp okay so we're going to choose lerp and you just type in and that's fine too we're going to do parentheses right in this particular case and we're going to say self okay dot X okay so the x position so self dot X and we're going to comma and then we're going to say player okay dot X all right and then we're also in this case going to comma and then we're going to do a 0.03 then that's the value that it kind of slowly works now the other lerp of course is the same thing so we're going to literally copy this so we don't to do it again that would be silly paste that in there instead of X we're going to change this to Y boom for Y and boom for Y so that's basically the coding you need to have the smooth camera work we'll just hit done so now you'll see that all there and now if we hit play alright let's maximize you see how the camera kind of follows the character so as I move right it's a little bit of a catch-up right I'm done and it just slowly kind of catches up with them up or down left or right it looks a little bit nicer than a camera this is like deadlocked on him and moving around so there you go we've got the character moving we got that smooth camera fall everything is ready to go so another video is kind of long but hopefully this really helped you guys understand how to create your platformer but yeah I guess I'll see you guys in the next video

Интерфейс Construct 2 на русском 🤖 Урок 1 🚀 Основы Construct 2



итак сегодня мы начинаем работу в программе конструкторы игр с кира construct 2 и в этом уроке мы рассмотрим основные элементы интерфейса нужные нам для создания игры работать мы будем по понятным причинам в free то есть бесплатной версии программы начнем и первое что нас встретят при открытии конструкт это стартовая страница но кому нужно эти стартовой страницы поэтому закроем и и и сразу же в настройках отключим и и автоматическое отображение при каждом запуске ах ты ж зараза ну ладно давайте хотя бы изменим вид программы потому что смотреть на этот белоснежный глаза выжигающий интерфейс просто невыносимо для этого переходим во вкладку view the в ленте сверху находим там пункт style и выбираем приятный темный интерфейс вот теперь можно начинать работать и сейчас для того чтобы рассмотреть основные части интерфейса программы создадим новый проект нажимаем кнопку file и выбираем пункт new как вы видите открылось окно с множеством различных шаблонов проектов почти все эти проекты представляют из себя обучающие исходники созданные разработчиками здесь вы например можете найти даже исходник нашумевшие когда-то игры flipping горд но нам нужен пустой проект со стандартными настройками поэтому жмем на нее mt project новый проект создан теперь давайте разбираться с тем что мы видим на экране во первых в самом центре экрана мы видим так называемую сцену это некоторое пространство в котором будут размещаться все игровые объекты то есть проще говоря это и есть сам уровень игры по бокам от сцены расположено множество всевозможных панелей который мы прямо сейчас рассмотрим начнем с панели project здесь в виде иерархии отображаются все открыты в данный момент проект и помимо этого каждый проект состоит из таких основных каталогов как уровне листы событий объекты семьи объектов звуки музыка и файлы со всеми этими категориями кроме семей мы поработаем следующих уроков семью мы использовать не будем так как бесплатная версия программ мы этого не позволят следующая панель по умолчанию находящиеся здесь отвечает за отображение всех доступных на данном уровне слоев то есть для каждого уровня набор слоев свой что же такое слой слой это некое пространство с помощью которого можно нужным образом группировать объекты то есть и разместив объекты на разных слоях вы можете прятать применять эффекты и тому подобное для конкретных слоев ну и разумеется объекты на верхнем слое будут перекрывать объекты находящийся на слоях ниже уровень слоев начинается с 0 on посмотреть вы его можете здесь также в этой панели помимо создания удаления и переименовывания вы можете убрать из видимости или заблокировать слой чтобы вы не могли взаимодействовать с объектами на этом слое в режиме редактирования подробнее с слоями мы поработаем в одном из следующих уроков сейчас давайте рассмотрим панель которая находится ниже это панель обжиг в ней исходя из названия находятся все объекты но принадлежащий тому уровню на котором вы сейчас находитесь поэтому тут важно заметить что объекты всегда без исключения создаются именно в проекте то есть вот в этой папке и но на уровне они создаются только тогда если вы либо создаете этот объект непосредственно на уровне либо если вы перенесете объекты с проекта на определенный уровень из-за незнания этого многие новички совершают ошибку при удаление объектов заключается она в том что когда вы удаляете последний экземпляр объекта со сцены он удаляется только из текущего уровня но при этом остается в проекте и даже если вы не вставили его не в один уровень то при экспорте он никуда не денется и будет бесполезно занимать свое место среди файлов игры будьте с этим внимательны удаляйте ненужные объекты именно из проекта ну и последняя основная панель называется properties отображает она настройки того что мы в данный момент выбрали то есть выбираем проект отображаются настройки проекта выбираем объект видим настройки объекта и так далее также обратите внимание на синюю панель внизу экрана на ней вы можете увидеть общее количество событий в вашем проекте на каком слое вы находитесь в данный момент а также положение по x и y курсора и процент масштабирования сцены иногда эти данные бывают необходимы основные части интерфейса мы рассмотрели теперь давайте обратимся к той панели который мы будем использовать наиболее часто это панель properties здесь мы рассмотрим ключевые параметры проекта и уровня начнем с уровня для этого кликаем либо на сцену так как сцена и то есть выбранный в данный момент уровень либо кликаем на нужный уровень в панели project теперь в панели properties отобразились настройки уровня здесь мы можем видеть такие параметры как имя уровня давайте переименуем его в володин и думаю следует упомянуть то что название уровнем объектом переменным и тому подобное нужно давать исключительно на английском языке дабы избежать ошибок при компиляции проекта продолжаем рассматривать параметры уровня и следующее интересующее нас в данный момент параметр это лайалл says то есть размер уровня давайте установим его на 2000 по x и тысячу по y как вы видите сцена моментально увеличилась на этом мы пока что оставим параметры уровня и перейдём к параметрам проекта кликаем на наш проект панели project и во-первых дадим имя проекту давайте назовем его как-нибудь сам незаурядно уникально креативно что ли по моему идеально и далее обратим внимание на такой параметр как превью браузер этот параметр определяет в каком браузере будет открываться превью вашего проекта то есть предпросмотр игры у меня превью браузер not web кит вы соответственно можете выбрать любой другой и последний нужно нам сегодня параметр это window сайт вы можете подумать что мы уже изменяли размеры окна в настройках уровня но если приглядитесь внимательнее к сцене то заметите вот этот пунктирный прямоугольник и то есть наше окно то есть та область которую при нормальном масштабирование охватывает игровая камер а сейчас размеры окна равны 850 на 480 давайте запустим превью я делаю это нажатием горячие клавиши f5 также можно нажать арам layout на вкладке home или в панели быстрого доступа нажимаем и как вы видите открылось окно привью как раз таки размер этого окна и настраивает параметр windows says а теперь давайте изменим размер окна пусть будет на 1280 на 720 опять запускаем превью и видим разницу ну что ж в этом уроке мы рассмотрели все нужные нам для последующих уроков элементы интерфейса поэтому смело можем отправляться к следующему уроку в котором мы уже наконец создадим персонажа и заставим его двигаться жду вас там и до встречи