Как создать игру похожую на plants vs zombies на unity

Обновлено: 03.07.2024

making a game following unity 3d plants vs zombies clone tutorial by blueteak

The Firing Plant

The Image

Alright let's create one more plant, the type that is able to shoot at the Zombies.

About

making a game following unity 3d plants vs zombies clone tutorial by blueteak

Resources

License

Creating the Grass

Grass in Project Area

Let's select the grass tile in the Project Area:

Grass Import Settings

And then modify the Import Settings in the Inspector:

Note: a Pixels to Unit value of 32 means that 32 x 32 pixels will fit into one unit in the game world. We will use this value for all our textures.

Drag Grass into Scene

Afterwards we can add the image to the game by dragging it from the Project Area into the Scene:

Grass Position in Inspector

We will position it at (0, 0) so it's at the bottom left of our game:

Adding a Sorting Layer

We are making a 2D game, so we can't use the third dimension as depth effect, or to distinguish between background and foreground easily. Instead we will use a Sorting Layer to tell Unity which elements it should draw first. For example, our background should be drawn first and the plants should be drawn afterwards (hence on top of the background).

Grass SpriteRenderer with default Sorting Layer

We can change the grass Sorting Layer if we take a look at the Sprite Renderer component in the Inspector:

Add Background Sorting Layer

Let's select Add Sorting Layer.. from the Sorting Layer list, add a Background layer and move it to the top like shown below:

Grass SpriteRenderer with Background Sorting Layer

Afterwards we select the grass again and assign the previously created Background Sorting Layer:

Note: Unity draws the layers from top to bottom, hence whatever should be in the background will be at the top of the list.

Now the grass will always be drawn behind the plants and the zombies.

Making the Grass clickable

Later on when working on the build menu we will need a way to find out if a grass tile was clicked. There are all kinds of different ways to do this in Unity, but the easiest one is to just use the OnMouseUpAsButton function that is automatically called by Unity if the grass was clicked.

Duplicating the Grass

Languages

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Releases

Как реализовать растения в игре типа Растения против Зомби? Юнити

Я хочу попытаться сделать игру по типу Растения против Зомби. Но не понимаю, как лучше и правильнее всего реализовать растения. В оригинальной игре их порядка 50 с лишним штук. Каким образом лучше это реализовать?

Думаю, можно сделать общий класс Plant, в котором создать переменные для названия растения, его урона, здоровья, спрайта и т.д., а потом для каждого объекта создавать экземпляр класса, указывая для каждого растения свои переменные? Но что сделать потом? Я создам префаб растения и какой скрипт в таком случае мне на него вешать?

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

Или можно. сделать еще как-то.


3,621 1 1 золотой знак 8 8 серебряных знаков 34 34 бронзовых знака Может сделать общий класс Plant, в котором создать переменные для названия растения, его урона, здоровья, спрайта и т.д., а потом для каждого объекта **создавать экземпляр класса, указывая для каждого растения свои переменные? - Двигаетесь в правильном направлении. Для даной задачи я бы советовал еще присмотреться к паттерну программирования "фабрика". Он именно для таких ситуаций и существует.

Вам придётся написать больше одного класса, но не для каждого растения.

Скрипт GameUnit просто содержит поле с префабом скина и ссылкой на скрипт Skin , объекта который он создаст из префаба, поле номера линии, количеством жизней, максимальных жизней, и функций получения урона и функцией смерти.

Ответственность класса Plant (наследуется от GameUnit ) проста: цена, функция построения и поле номера клетки.

Skin с функциями проиграть rise, idle, walk, attack, dead настроенные под скин и для растений и для зомбаков.

PlantBehaviour просто находит класс Plant и хранит на него ссылку, для получения ссылки к скину и тайлу(линия и клетка).

AttackBehaviour умеющий палить врагов на своей линии что заставляет стрелять наследуется от PlantBehaviour . Растения у которых какие-то необыные атаки (например атакуют врагов на всех линиях или соседних) имеют свой скрипт наследуемый от AttackBehaviour и меняют фунции палева врага или спавна снаряда.

У добытчиков скрипт HarvestBehaviour , наследуемое всё от тогоже PlantBehaviour .

У мин свой скрипт, а стенкам поведение вовсе не нужно.

Zombie тоже наследуются от GameUnit . Реализует атаку другого GameUnit .

У зомбаков свои скрипты передвижения как поведения растений и дополнительных фич типа щита и т.д.

Creating a Sunflower Plant

Drawing the Animation

Since we are developing a 2D game, animations are very easy to make with our drawing tool of choice and a few hours of time.

Pixel Art Sunflower Plant

For our sunflower we will only need an idle animation where its head slightly moves. Here is what we came up with:

Note: right click on the image, select Save As. and save it in the project's Assets/Sprites folder.

Sunflower ImportSettings

Let's select the sunflower image in the Project Area and then modify the Import Settings in the Inspector:

The Filter Mode and Format influence the looks. Setting the Sprite Mode to Multiple tells Unity that there are several sunflower parts (also known as Tiles) in one image.

Importing the Animation

Now we have to tell Unity where those tiles are in the image. We can open the Sprite Editor by pressing the Sprite Editor button in the Inspector (it can be seen in the above image).

Sunflower in Sprite Editor

Afterwards we can see our Sunflower in the Sprite Editor:

Sunflower Sprite Editor Slicing

All we have to do here is open the Slice menu, set the type to Grid and the pixel size to 32 x 32. Afterwards we press the Slice button:

Let's press Apply and then close the Sprite Editor.

Sunflower Project Area Slices

If we take a look in the Project Area then we can see that our Sunflower now has 2 children (the slices):

Creating the Animation

Create Sunflower Animation

Creating a Unity Animation from those 2 slices is incredibly easy. All we have to do is select them in the Project Area and then drag them right into the Scene:

Once we drag it into the scene, Unity asks us where to save the Animation. We can create a new SunflowerAnimation folder in our Project Area and then save it as idle.anim.

Sunflower Animation Files

Unity then creates two files for us:

This is what our animation looks like if we press Play:

Note: we can modify the animation speed by double clicking the sunflower_0 file in the SunflowerAnimation folder, selecting the idle state and then changing the speed in the Inspector.

Physics, Tags and Health

Our plant should be part of the physics world, which means that we have to assign a Collider to it. A Collider makes sure that things will collide with the plant and that the plant will collide with other things.

Plants Collider

Let's select the plant and then press Add Component->Physics 2D->Box Collider 2D in the Inspector:

Plants untagged

We will also need to find out if a certain GameObject is a Plant, a Zombie or something completely different. This is what Unity's Tag system is for. If we take a look in the Inspector, we can see that the current tag is Untagged:

Plants Tagged

We can assign the Plant tag by selecting Add Tag. in the Tag list, then adding the Plant tag to the list of available tags, selecting the plant again and then assigning the Tag from the Tag list:

Health Script in Inspector

Finally we will select Add Component->Scripts->Health in the Inspector, so the Zombies can deal damage to the plant later on:

Note: our Sunflower was just placed somewhere randomly in the Scene. We will keep it in there for now as long as we are working on the sun spawns in the next step. Proper positioning on a grass tile will be implemented later on.

The Health Script

The Zombies should be able to attack the Plants, and the Firing Plant should be able to deal damage to the Zombies. We will stick with Unity's component based nature and create only one Health script for all entities.

Health Script in Project Area

We will name it Health and then move it into a new Scripts folder:

We can open and then modify the Script by double clicking it:

We won't need the Start or the Update function, so let's remove both of them. Instead we will add a int variable that keeps track of the current health and add a function that decreases that variable. If the current health drops below 0 then the entity should be destroyed:

Note: we used SerializeField to let Unity know that we want to be able to modify the cur variable in the Inspector. Usually this is done by making it public, but in this case we don't want other Scripts to be able to access the cur variable. Instead they should always use the doDamage function.

The Script will be added to all Plants and Zombies later on.

Unity 2D Plants vs. Zombies Tutorial

Unity Plants vs. Zombies

Today we will make a Plants vs. Zombies clone with Unity's 2D features. To keep things simple, we will ignore all the fancy things like the menu, multiple levels or cut-scenes and focus on fighting Zombies in the backyard. The Tutorial will be really long and detailed, but the end result will be less than 130 lines of code!

Here is a preview of the game:

Requirements

Knowledge

This Tutorial does not require any advanced knowledge. A basic understanding of the Unity engine is still required. Feel free to read our easier Unity Tutorials like Unity 2D Pong Game to get used to the engine.

Unity Version

We will use Unity 5.0.1f1 in this Tutorial. Newer versions should work fine as well, older versions may or may not work. The free version of Unity 5 now comes with all the engine features, which makes it the recommended version.

Project Setup

Unity New Project

Let's start working on the game. We will start Unity and select New Project:

Camera Properties

If we select the Main Camera in the Hierarchy then we can set the Background Color to black, adjust the Size and the Position like shown in the following image:

Как сделать идеальный туториал? Советы от PopCap (вторая часть)!


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

Первую часть материала можно найти здесь.


6. Не стоит быть навязчивым

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

7. Используйте адаптивную систему подсказок

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

Во время игрового теста Plants vs. Zombies Фен обнаружил, что некоторые игроки не понимают, что растения следует сажать с левой стороны экрана. Чтобы решить эту проблему, он разработал систему подсказок, которая срабатывает лишь в том случае, если игрок начинает делать что-то неправильно.

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


8. Не раздражайте игроков

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

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

9. Используйте визуальные образы

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

И подобный подход, по словам Фена, применим к каждому персонажу игры, от здорового Screen-Door Zombie (Screen-Door – парадная дверь) до энергичного Coffee Bean (кофейный боб).


10. Используйте то, что люди и так знают

По сути, Plants vs. Zombies – очередная вариация на тему tower defense, но еще при ее разработке Фен хотел, чтобы игрокам с самого начала было ясно, почему башни не могут двигаться, а нападающие столь неторопливы.

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

Так и получилось, что и те, и другие – идеальные персонажи для игры в жанре tower defense.

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

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


Сам Фен считает, что если следовать при создании туториала всем этим советам, то любую игру можно сделать столь же простой в освоении, какой является Plants vs. Zombies.

Spawning Suns

Drawing the Sun

Pixel Art Sun

The Sunflower plant is supposed to spawn a new sun every few seconds, so let's start by drawing one:

Note: right click on the image, select Save As. and save it in the project's Assets/Sprites folder.

Sun ImportSettings

We will use the following Import Settings:

The Foreground Layer

Add Foreground Sorting Layer

We want the sun to be drawn in front of the background and in front of the plants. Let's click on Add Sorting Layer.. again and create another Sorting Layer, name it Foreground and move it to the bottom of the list:

Sun Sorting Layer

Afterwards we can select the sun again and assign the Foreground Sorting Layer to it:

Creating the Prefab

Sun Prefab in Inspector

Now we take a look at the Inspector where we rename it to SunPrefab and press the Add Component button where we select Physics 2D->Circle Collider 2D. A Collider allows us to do some physics stuff with the Sun later on:

Note: In the original Plants vs. Zombies game the Sun doesn't really collide with the plants or the zombies. We can achieve this behavior by selecting Is Trigger in the Circle Collider 2D. This means that the sun receives collision information, but never really collides with anything. The zombies will be able to walk right through it, instead of colliding with it.

Create Sun Prefab

Afterwards we drag it from the Hierarchy into a new Prefabs folder in the Project Area to create a Prefab:

Now we can delete it from the Hierarchy.

Note: the sun will later be loaded into the Scene by using the Instantiate function. We can't just use the Sun Texture because we really do need a GameObject with Colliders and everything.

Creating the Spawn Script

New Script

We want the sunflower to spawn a new sun every few seconds. This kind of behavior can be implemented with Scripting. Let's select our sunflower and then click on Add Component->New Script:

We will name it SunSpawn, select CSharp as the language and then move it into our Scripts folder in the Project Area. Afterwards we will open it:

We will add a public GameObject variable that allows us to specify the Prefab later on in the Inspector:

The Instantiate function allows us to load a Prefab into the Scene. The InvokeRepeating function allows us to call a certain function repeatedly, starting at some time in the future. For example, if we would want to spawn something the first time in 1 second and then repeat that every 2 seconds, we would use InvokeRepeating("Spawn", 1, 2). We want the first sun to be spawned in 10 seconds and then keep spawning more suns every 10 seconds, so here is our code:

Sunflower SunSpawn Script Prefab

Now we can save the Script and take a look at the Inspector again. The Script has a Prefab property because our prefab variable was public. Let's drag our SunPrefab from the Project Area into the Prefab slot of the Script:

If we press Play then we can see a new Sun spawn every 10 seconds.

Sun Movement

After a sun spawned it should slowly fade away towards the top of the screen. We will use a Rigidbody2D for that. A Rigidbody is usually used for everything in the physics world that is supposed to move around.

Sun Rigidbody

Let's select the sun in the Project Area and then click on Add Component->Physics2D->Rigidbody2D in the Inspector. We will assign the following properties to it:

Note: we set it in each FixedUpdate call so that whatever has this script attached to it will try to keep moving no matter what happens. This is useful for the Zombies that might not be able to keep moving when running into a plant, but our Script will make sure that they start moving again as soon as the plant was destroyed.

Sun DefaultVelocity Script

Afterwards we select the sun prefab again and then add the Script to it by clicking on Add Component->Scripts->Default Velocity. We will also assign a velocity that goes upwards (into the y direction):

If we press Play then we can now see the sun spawn and move upwards afterwards:

Collecting Sun

The last thing we have to do when it comes to the sun is to allow the player to collect it. We will need one global score that keeps track of how many suns were collected, and we will need to increase that score whenever the player clicks on a sun.

Note: we have to use static in order to make the score variable global. This means that it can be accessed by other scripts with SunCollect.score any time. The initial score value is 100 so the player has some sun to start building plants with.

Once we added the Script to the sun Prefab we can press Play, wait for a sun to spawn and then collect it by clicking on it.

Cleaning Up the Hierarchy

Sunflower Prefab

Right now the Sunflower is still in the Hierarchy, but we don't want it to be in there from the beginning. The player is supposed to build it manually later on. So let's create a Prefab from it by dragging it into the Project Area:

Premium Tutorial

Enjoyed this preview? Become a Premium member and access the full Unity 2D Plants vs. Zombies Tutorial!

All Tutorials. All Source Codes & Project Files. One time Payment.
Get Premium today!

Packages 0

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