Android App and Game Development Tutorials (Skill Level: Beginner and Intermediate)
Java is arguably the most common programming language used to create Android apps. Lucky for you, we’ve already done some legwork and put together a similar article for exclusively Java tutorials. If you haven’t checked that article out already, we highly recommend it.
There are indeed other ways to develop games for Android, but you will without a doubt benefit from learning Java.
This article has several useful tutorials exploring different programming environments. Before you get started on this, you’ll want to make sure you have the Android Software Development Kit or SDK. Alright, now it’s time to rock!
Table of Contents:
Tutorials for Android Engines
Udacity
Have you guys heard about Google? You have? Oh good, then you know that Google does some pretty neat things. One of those things is providing this Udacity nanodegree program.
It’s a course called “Developing Android Apps.” It’s about 60 hours worth of course material, with a skill level catering to those with “intermediate” ability (not at “intermediate” yet? Skip the next two paragraphs and read the fourth one!).
The course focuses on Android app development rather than specifically game development. It will teach you how to build a solid app, and it will teach you the technically correct way to do it. The Udacity approach combines the necessary theory with actual, hands-on practice, so your learning is reinforced (and hopefully absorbed).
They make it convenient to learn, too, with the Udacity app for mobile. You can learn away from your computer. Not too shabby!
This program does come with some recommended prerequisites, as denoted by its intermediate ranking. They recommend at least one year of programming experience in C++, Java, or other programming languages that are largely object-oriented.
Since we’re not all intermediate, take a look at this beginner’s course from Udacity! Did we scare you off with all that intermediate talk? We hope not. The beginner’s course was also made in collaboration with Google. The beginner’s program takes about 4 weeks. At that time the course will teach you how to build two apps.
This is a great course to take if you don’t have any experience and don’t even know what you’re getting yourself into with Android game development.
KiloBolt
This here is a free tutorial that hasn’t been created by Google. This course was instead authored by James Cho, the lead developer at Kilobolt Studios. In this java/android game development tutorial, you will develop a game, in Java, and learn how to port it to Android. The best part is you can bounce around to different starting points based on your experience.
If you have no game development experience, you can start at the beginning. Unit 1 is “beginning Java.” If you have a little bit of Java experience, but you haven’t made a game yet, you can start with Units 2 and 3, “Creating a Game I” and “Creating a game II,” respectively.
If you’re already an experienced Java game developer, but you want to learn how to port to Android, you can skip right to Unit 4 of KiloBolt’s tutorial, “Porting to Android.”
The tutorial itself is several years old, which means the KiloBolt forums no longer “officially” support the topic in their forums. The content in the tutorial will work just fine for you, and you can still ask questions in the forum if you get stuck, but answers will only come on the whim of other forum participants.
The author does provide his email address, so if you’re stuck or you have a dynamite question, you could always try and reach him there.
This is an easy resource to browse for free to get the gist of it, so whether you’re a beginner or an intermediate Java coder, check out this guide for its Android-porting potential.
Futurelearn
Futurelearn is a website that offers a wide variety of different courses. Their most relevant offering for Android game development is a course called “Begin Programming: Build Your First Mobile Game.” This is another course that teaches Java programming language to develop an Android game.
This course is online and completely free. It was created by the University of Reading. It’s a seven-week course, requiring about four hours per week. There are certificates of completion available if that’s something that tickles your fancy. While the certificates of completion cost money, the course itself is free to take.
This course is not self-paced, so you won’t have quite as much flexibility as with the self-guided tutorials. The most recent class started back on October 31st. At the time of this article, the next class start time is still TBA. They do give you the option to “register interest.”
If you’re serious about wanting to take it, you should let them know so they schedule another class sooner rather than later. When the time is right, we expedite! What if all of you RSVP your interest at the same time and then you all end up in the same class when it opens back up? Talk about perfect!
You can take this course without any prior coding knowledge, it will teach you the basics. The course does mention that you’ll need to “be comfortable downloading, unzipping and installing software to your computer.” As long as you’re OK with that, and don’t mind putting the effort in, this sounds like a great learning opportunity.
Android
Looking for “official” Android development help? Android’s Developer page will walk you through building your very first Android app. This tutorial teaches you how to use Android Studio (which you were supposed to download and install already!). If you haven’t downloaded anything yet, you can do it right from the Building Your First App page.
The Android tutorial, as you might expect, is focused on app development, not game development. If you’re looking to get right to game development, you should start with a different tutorial on this list.
Udemy
Udemy is a great resource for you to look into when you’re trying to learn a new skill. They offer some free courses, some cheap courses, and some…well…expensive courses. They also have sales, deals, and coupons floating around all the time!
At the time that this article was written, for example, Udemy was running a Black Friday sale on this course (and many, many others). The price was just $13, and the prices were increasing every other day until Black Friday (the regular price is $195, so this was a rock-solid deal).
This course, Master Android 7 App Development With Java, has the following tagline “Become an Android Nougat Developer, Learning to write apps and games with Android N using Google’s Android Studio.” If that doesn’t get you excited, we just don’t know what will.
The course is approximately 40 hours in length, with 213 lectures. It’s open to all levels, and they iterate several times that no prior programming experience is necessary.
The price for the course includes the certificate of completion, and there’s a 30-day money-back guarantee. So if you take it and hate it, return it! If you like it, you have the benefit of lifetime access.
If you’re hungry for more from Udemy, Here are two other course options to pique your interest:
Источник
Туториал: Создание простейшей 2D игры на андроид
Этот туториал предназначен в первую очередь для новичков в разработке под андроид, но может быть будет полезен и более опытным разработчикам. Тут рассказано как создать простейшую 2D игру на анроиде без использования каких-либо игровых движков. Для этого я использовал Android Studio, но можно использовать любую другую соответствующее настроенную среду разработки.
Шаг 1. Придумываем идею игры
Для примера возьмём довольно простую идею:
Внизу экрана — космический корабль. Он может двигаться влево и вправо по нажатию соответствующих кнопок. Сверху вертикально вниз движутся астероиды. Они появляются по всей ширине экрана и двигаются с разной скоростью. Корабль должен уворачиваться от метеоритов как можно дольше. Если метеорит попадает в него — игра окончена.
Шаг 2. Создаём проект
В Android Studio в верхнем меню выбираем File → New → New Project.
Тут вводим название приложения, домен и путь. Нажимаем Next.
Тут можно ввести версию андроид. Также можно выбрать андроид часы и телевизор. Но я не уверен что наше приложение на всём этом будет работать. Так что лучше введите всё как на скриншоте. Нажимаем Next.
Тут обязательно выбираем Empty Activity. И жмём Next.
Тут оставляем всё как есть и жмём Finish. Итак проект создан. Переходим ко третьему шагу.
Шаг 3. Добавляем картинки
Скачиваем архив с картинками и распаковываем его.
Находим папку drawable и копируем туда картинки.
Позже они нам понадобятся.
Шаг 4. Создаём layout
Находим activity_main.xml, открываем вкладку Text и вставляем туда это:
На вкладке Design видно как наш layout будет выглядеть.
Сверху поле в котором будет сама игра, а снизу кнопки управления Left и Right. Про layout можно написать отдельную статью, и не одну. Я не буду на этом подробно останавливаться. Про это можно почитать тут.
Шаг 5. Редактируем MainActivity класс
В первую очередь в определение класса добавляем implements View.OnTouchListener. Определение класса теперь будет таким:
Добавим в класс нужные нам статические переменные (переменные класса):
В процедуру protected void onCreate(Bundle savedInstanceState) <
добавляем строки:
Классы LinearLayout, Button и т.д. подсвечены красным потому что ещё не добавлены в Import.
Чтобы добавить в Import и убрать красную подсветку нужно для каждого нажать Alt+Enter.
GameView будет подсвечено красным потому-что этого класса ещё нет. Мы создадим его позже.
Теперь добавляем процедуру:
Если кто-то запутался ― вот так в результате должен выглядеть MainActivity класс:
Итак, класс MainActivity готов! В нём инициирован ещё не созданный класс GameView. И когда нажата левая кнопка — статическая переменная isLeftPressed = true, а когда правая — isRightPressed = true. Это в общем то и всё что он делает.
Для начала сделаем чтобы на экране отображался космический корабль, и чтобы он двигался по нажатию управляющих кнопок. Астероиды оставим на потом.
Шаг 6. Создаём класс GameView
Теперь наконец-то создадим тот самый недостающий класс GameView. Итак приступим. В определение класса добавим extends SurfaceView implements Runnable. Мобильные устройства имею разные разрешения экрана. Это может быть старенький маленький телефон с разрешением 480×800, или большой планшет 1800×2560. Для того чтобы игра выглядела на всех устройствах одинаково я поделил экран на 20 частей по горизонтали и 28 по вертикали. Полученную единицу измерения я назвал юнит. Можно выбрать и другие числа. Главное чтобы отношение между ними примерно сохранялось, иначе изображение будет вытянутым или сжатым.
unitW и unitW мы вычислим позже. Также нам понадобятся и другие переменные:
Конструктор будет таким:
Метод run() будет содержать бесконечный цикл. В начале цикла выполняется метод update()
который будет вычислять новые координаты корабля. Потом метод draw() рисует корабль на экране. И в конце метод control() сделает паузу на 17 миллисекунд. Через 17 миллисекунд run() запустится снова. И так до пока переменная gameRunning == true. Вот эти методы:
Обратите внимание на инициализацию при первом запуске. Там мы вычисляем количество пикселей в юните и добавляем корабль. Корабль мы ещё не создали. Но прежде мы создадим его родительский класс.
Шаг 7. Создаём класс SpaceBody
Он будет родительским для класса Ship (космический корабль) и Asteroid (астероид). В нём будут содержаться все переменные и методы общие для этих двух классов. Добавляем переменные:
Шаг 8. Создаём класс Ship
Теперь создадим класс Ship (космический корабль). Он наследует класс SpaceBody поэтому в определение класа добавим extends SpaceBody.
и переопределим метод update()
На этом космический корабль готов! Всё компилируем и запускаем. На экране должен появиться космический корабль. При нажатии на кнопки он должен двигаться вправо и влево. Теперь добавляем сыплющиеся сверху астероиды. При столкновении с кораблём игра заканчивается.
Шаг 9. Создаём класс Asteroid
Добавим класс Asteroid (астероид). Он тоже наследует класс SpaceBody поэтому в определение класса добавим extends SpaceBody.
Добавим нужные нам переменные:
Астероид должен появляться в случайной точке вверху экрана и лететь вниз с случайной скоростью. Для этого x и speed задаются при помощи генератора случайных чисел в его конструкторе.
Астероид должен двигаться с определённой скорость вертикально вниз. Поэтому в методе update() прибавляем к координате x скорость.
Так же нам нужен будет метод определяющий столкнулся ли астероид с кораблём.
Рассмотрим его поподробнее. Для простоты считаем корабль и астероид квадратами. Тут я пошёл от противного. То есть определяю когда квадраты НЕ пересекаются.
((x+size) (shipX+shipSize)) — корабль справа от астероида.
((y+size) (shipY+shipSize)) — корабль снизу астероида.
Между этими четырьмя выражениями стоит || (или). То есть если хоть одно выражение правдиво (а это значит что квадраты НЕ пересекаются) — результирующие тоже правдиво.
Всё это выражение я инвертирую знаком!. В результате метод возвращает true когда квадраты пересекаются. Что нам и надо.
Про определение пересечения более сложных фигур можно почитать тут.
Шаг 10. Добавляем астероиды в GameView
В GameView добавляем переменные:
также добавляем 2 метода:
И в методе run() добавляем вызовы этих методов перед вызовоом control().
Далее в методе update() добавляем цикл который перебирает все астероиды и вызывает у них метод update().
Такой же цикл добавляем и в метод draw().
Вот и всё! Простейшая 2D игра готова. Компилируем, запускаем и смотрим что получилось!
Если кто-то запутался или что-то не работает можно скачать исходник.
Игра, конечно, примитивна. Но её можно усовершенствовать, добавив новые функции. В первую очередь следует реализовать удаление вылетевших за пределы экрана астероидов. Можно сделать чтобы корабль мог стрелять в астероиды, чтобы игра постепенно ускорялась, добавить таймер, таблицу рекордов и прочее. Если это будет вам интересно — напишу продолжение, где всё это опишу.
На этом всё. Пишите отзывы, вопросы, интересующие вас темы для продолжения.
Источник