How to make Space Invaders in Unity (Complete Tutorial) 👾🛸
Vložit
- čas přidán 8. 07. 2024
- Learn to make the classic 2D arcade game Space Invaders in Unity. Space Invaders is a 1978 shoot 'em up arcade game developed by Tomohiro Nishikado. Within the shooter game genre, Space Invaders was the first fixed shooter and set the template for the shoot 'em up genre. The goal is to defeat wave after wave of descending aliens with a horizontally moving laser to earn as many points as possible.
0:00 - Introduction
0:41 - Project Creation
1:16 - Scene Setup
9:35 - Invader Prefabs
15:09 - Invader Animation
22:02 - Invader Grid
32:36 - Invader Movement
41:04 - Player Movement
43:40 - Laser Shooting
56:49 - Killing Invaders
1:07:46 - Missile Attacks
1:15:16 - Game State
1:24:00 - Outro
NOTE: I accidentally left one clip out of the video of me adding a Rigidbody2D component to the "Invader_Base" prefab. For collisions to occur, at least one of the colliding objects needs a rigidbody. Set the "Body Type" property to "Kinematic" on the rigidbody so the movement of the invaders is not simulated by the physics engine.
🖥️ Source code and assets: github.com/zigurous/unity-spa...
👍 Subscribe for more Unity tutorials: czcams.com/users/zigurous?sub...
💬 Join our Discord community: / discord
👑 Become a Patreon supporter: / zigurous
❤️ Support my work: www.paypal.com/donate?hosted_...
⭐ Download my Unity assets: zigurous.com/assets
····················································································
► Learn more about my work: zigurous.com
► Follow for news and updates: / zigurous
#unity #unitytutorial #gamedev #unity3d #unity2d #gamedevelopment #indiegame #indiedev #madewithunity
Visit the GitHub page for the most up to date source code: github.com/zigurous/unity-space-invaders-tutorial
View the FAQ for answers to common questions: github.com/zigurous/unity-space-invaders-tutorial/wiki
I literally came to this video to see how you handled the bunker physics because I'm making my own clone of Space Invaders, only to realize that's one of the only things you left out of here lol
This makes a REAAAALLY good way of learning unity. As humans, examples are the ultimate best way for learning things. I wish schools knew that
AWESOME! Best game development tutorial series i've ever seen.
Hey mate, havnt watched much yet but the little I watched definilty want me do keep follow the stuff you post. Keep it up. I guess my evening will be spent watching all the stuff you did so far.
Thanks for the Space Invaders tutorial, it was really well explained. I learned a lot!
I accidentally left one clip out of the video of me adding a Rigidbody2D component to the Invader_Base prefab. This is needed in order for collisions to work between the invaders and the player. Alternatively, you could add the rigidbody to the player game object. Either object will enable collisions between the two. You will also want to set the rigidbody type to "Kinematic" since we don't actually want the movement of the object to be simulated by the physics engine.
In general, for collisions to occur between two objects at least one of those objects needs a rigidbody. The rigidbody turns the object into a physics object, and it is the physics engine that calculates collisions. Sorry for the mistake! Let me know if you have any further questions.
Rigidbody2D should only be on the player since its moving
when does this need to be done
@@drradium1616 At any point. As soon as you've created your Invader prefab you can add the Rigidbody2D component to it.
@@Zigurous thanks, you should make more videos, these are the best tutorials i've found
@@Zigurous also do you mean the invader base prefab?
Nicely done! Used to play around w/ XNA years ago, and just now dabbling with Unity. Great tutorial! Sincerely appreciate your time on this.
Easy to follow tutorial once again, for beginner like me 👍 Learned a lot about prefabs 🧠
Amazing! This was my second tutorial from you and you are an absolutely amazing teacher! Thanks a million for taking the time and posting these. You're a rock star.
one of the best teachers i've ever had in my life
Just finished The Asteroids, Pong, and Snake ones and am excited keep going with this one aswell.
This was a solid tutorial. Thanks man.
THANKS MAN!!!
I appreciate all your videos
NICEEEEEEEE!!!!!!!
Thank you so much, this is awesome!
Great tutorial! I learned a lot. Thank you.
Thanks man cant wait for more arcade games tutorials pacman and others watching your videos i manage to understand how to make my games byutifull sprites are better camera size everyithing is going well on developing my first game 😊❤️ Missile Command tutorial would be great too
Wow what an amazing tutorial, I just finished it.
Amazing once again.
I hope someday you could make videos for advanced stuff too. Of course it is really fun trying to figure out by myself how to make things work.
Thank you!
I certainly will be making videos of more advanced things in the future.
i loved this so much, thank you so much
Thank you for providing these high effort tutorials for free! I will sub to patreon in a few months when my financial situation is a little better :)
Fyi the new input system works very well with your tutorials and might help some new peeps get used to it, anywho great tutorial
Millepede would be an excellent retro -project for many to tackle and admire.
Hey Zigurous,
Amazing Video as always :D
It'd be great if you could make a tutorial for the full game state as you have mentioned.
Thanks :)
Ps beginner first time on unity . Thank you for doing tutorials to teach even total beginners
THE MOST ORGANIZED AND CLEAN TUTORIAL EVER THIS IS AMAZEBALLS
I made this one. So fun
why just 571 views this is one of the best tutorials ive ever seen (sorry about my english)
Because it has only been up for a very short time? I am sure its view count will increase over time.
@@HKragh you were right!
saved the day🥶🥶👀👀🎉🎉
I think this guy might be like a genius or something? He just codes straight from his head lol
Instead of the destroying bunker physics i came up with a idea to shrink the size of the bunker and after the size shrinks 3 times it explodes. It is very cool and very easy to make.
I am very curious to know how you did the bunkers and tried looking up some stuff. Would it be done using something called "Layer Masks"? It sounds like it may be what you used, just wondering if I should look into this area as a way of doing the bunkers, thanks
I loved youre tutorials, really helps me learn the basics and also motivates me to add onto it afterwards.
I didn't fully understand why you had to substract a row/col when defining the width/height, I tested without it and it doesnt center properly, but I wanted toi know if you could tell me the logic behind it.
Thank you tons
Hello, I have a question. I'm at the part where you make several layers so that the laser gets collisions with the invaders etc. But my laser is colliding with my bunker and the boundary but not with the invaders. Pls can you help me!
This is awesome! Thank you! Can you do Galaga at some point?
Galaga would be a fun one. I'll definitely consider it!
Hi. What VS code extension do you use to get code completion for Unity?
what if I wanted them to endlessly respawn when they were all dead with some incremental stat updates? e.g. they start a bit faster or even the enemy order changes etc?
Hello, I'm having a hard time with the actual sprites, the files have the propper icon but when I open them up I can see no image, and when I add them in the game, same problem
Do you know how you would go about adding the ever increasing 'bum' 'bum' beat with the original space invader music.
As enemies died the beat got faster and faster I was wondering if you perhaps had any knowledge you could share of a way to implement this.
First of all, thank you very much for such a sharing, I also have a question, when we hit all the spaceships, the game does not restart, where do you think I should check in this case? Since I'm new to game development, I haven't found the problem yet. Do you have any advice for me? I wonder in which code and which part of the code may be missing? or in unity? Thank you again.
How do i add the bunker affect to other objects
I know this is a late reply but i hope you can help me. Ive set up everything in the game. Everything works but when the invaders go all the way down to the bunkers. For some reason the bunkers dont 'SetActive(false);' Can you tell me why that might be the case. Ive set all the game up all right including the grid for the layers etc
I had the same problem ... he forgot to show adding a Rigidbody2D component to the Invader_Base prefab.
45:48
why do you use This.position, this.speed, this.direction
when refering to variables for the projectiles own variables when it would seem to be not needed? the This tag looks like it is needed in specific areas but i dont know when. what is it for
Your first three videos were amazing!!! This video felt rushed and you did not explain things like in your previous videos. You are a really good teacher. You just did not see like you were into making this one.
i am doing a class project and i don´t know about programming so i´m using this video to help me, well i´ve done the exact same things the exact same way and there´s some errors that don´t let me do anything and it´s just at the beggining, the animations
I'm sorry, can anyone help me better understand exactly what the Invoke function does in the projectile script?
I'm new to this and I didn't fully understand.
Guys, if your sprites do not show inside your game view at the same positions that he did in the video, make sure in the MainCamera that the size is set to 15. Mine was set to 5 by default and I could not figure out what was going on.
When I create project there is no templates that show up at all just lets me name project but what is showing on left with templates isn't there.
hi, i am getting very frustrated because the speed animatioCurve graph thing wont save the changes i make when i edit it and all my code is the same, i have no errors, and i restarted unity, but nothing works. can someone please help me.
i can't give mine invader to invaders form make the grid, what can i do?
Hi! I'm pretty new at this and I appreciate the constant explanation, helps me understand how everything works and when do I need certain things. Although, while I'm sure I followed all the steps, the scripts don't seem to work. Had to skip the animation code because there wasn't any "box" to drag them into and now, at the Invader Grid, I can't specify which Prefabs I want, only change the number of Rows and Colums. Could it be that certain words aren't highlighted in the code (Instantiate, for example) and so they just... don't do anything? How should I approach this? Ty for your time
If certain fields aren't showing up in the editor for you to drag stuff into it might be that the variables in your code are not marked with the public keyword. If you want you can post your code here and I see if I notice any problems.
hey I'm having a bit of a hard time at the bunker destruction, I tried making the script myself and it didn't work so I got your script and it still doesn't work. idk what to do anymore lol pls helppp
Thanks for your great work! I'm starting off with Unity and I guess it's reasonably straight forward to add sounds? cheers
Yea it's not too difficult to add sounds. You'll add AudioSource components to your scene which play an AudioClip asset. There are a number of settings on the component you can change. You can have the audio play on awake, or you can tell them to play manually via code.
@@Zigurous Thanks so much! I'll keep watching your videos: )
Why loop through all invaders in Update() to see if they hit the edge? Couldn't you just have a OnTriggerEnter2D() on the boundary and check for the Invaders tag?
Yes you could use OnTriggerEnter2D with a collider. One thing that would be important is making the collider size match the bounds of the grid of invaders. For example, if you cleared an entire column on one of the ends, the total bounds would need to be shrunk and repositioned.
So far at 32:45. Great tutorial so far!
I meant to say 53:53
👾🛸
Does anyone know how we can implement the original space invaders jittery movement that makes each row move one after the other, by modifying the smooth movement we have in this version, have an issue selecting each row.
P.S- Great tutorial on space invaders
The "jittery" movement was because each individual invader moved one at a time, not row by row, or all of them at once. Always makes me laugh that pretty much every single Space Invader tutorial gets this wrong
arg... i am stuck!!! After writing my script code and transferring to the prefab.... The Animation Sprites doest show at all!!! is it because i am writing the code wrong? I have double check it and its just like yours... any advice? P.S. I love your videos... let me know if you want a collab.... Cheers
hello my dear friend
I used your video and designed the game, but in the Invaders coding part, I ran into a problem and faced the indexoutofrange error. Can you please guide me?
what does adding a function to a system action like killed or destroyed do?
and what does invoke() do?(sorry for all the questions, im just very new to c# and code in general)
At 25:21 you drag your invader prefabs into the gameobject, for some reason when I try to do this it will not let me add my invaders into the elements. If I click on the circle next to where it says "none (Invader)" it says I don't have any prefabs available to add, despite the fact that I have several prefabs that I have made. Can anyone help me with this?
I think it is because it is expecting the prefab to contain the Invader script. Maybe your prefab object doesn't have that on it.
@@Zigurous That worked thanks!
@@Zigurous My prefabs have the invader script in them but they still won't add to the element
For the invaders script I have written the exact same code however when the invaders go off screen they do not change direction
I'd have to see some of the code to identify what might be causing the error. If you want you can post your code in our Discord server, discord.gg/DdYyWVb.
Or you can try posting the Update function of your Invaders script here as a comment.
@@Zigurous Hello, I have the same problem, have you found any solution for this?
I did the entire tutorial but at the very end it won't let me use "using UnityEngine.SceneManagement;" in my code. Does anyone know the fix to this?
is it normal that the sprites are deformed in my Game window ?
at 1:18:37, I kept getting the error
Assets\Scripts\Player.cs(44,13): error CS0103: The name 'other' does not exist in the current context
anyone else get this, or did I just mess up?
y
You'd have to show the code for us to help, but i think You named the parameter of the function another name than "other"
Did you solve this issue? I have the same error but in my Invaders script “Instantiate(missilePrefab, invader.position, Quaternion.identity); return;
It says “invader” does not exist in the current context.
yooo is it alright if i mention u in my video cause imma be making space invaders 2021 version
Absolutely, that would be awesome!
Now I'm doing something like Space Invaders, but in a different way, I want different enemies with different locations to appear, I also want there to be Esports for this game and where athletes can roam) I call this my game: *ORBIT SPACE WAR*
This is very well done. No overexplaining stuff that I can easily look up. I hate the tutorials geared to the slow kids in the class.
I was looking for the one part you missed out of the tutorial, the bunker damage. A repo isn't enough :(
Can you do 1 adding audio please? ive been looking for days now
After switching scenes the Projectile gets destroyed even without colliding with anything
Next video should be a tutorial on game over screens and menus
I have added a simple game over menu with my Frogger tutorial czcams.com/video/GxlxZ5q__Tc/video.html
if I made the invaders move by animation . Would this be easy?
I believe that would still work yea. Using that approach you could maybe make some cool movement patterns for the invaders.
at 46:38 , if you don't need rotation / it isn't necessary, why did you write [ Quaternion.Identity ] while in the invaders script, you didn't write anything for the third argument at 24:35
I dont understand how I import the sprites into my unity project
is there an easy way?
If you have any image file like a png or jpg, you can drag them from a folder into your assets folder. You can also use the menu Assets > Import New Asset..
@@Zigurous thank you bro
Hi!! I'm watching lesson one. I'm developing a snake game. Copied the code all as you have and after running the snake (Green Cube) escapes beyond the coordinates. I can't solve this problem.
If your snake is going beyond the edge of the area, then you are probably missing the correct components needed to detect collisions between those objects. Make sure your wall game objects each have a BoxCollider2D component on them with the "Is Trigger" property checked on. The snake game object should also have a BoxCollider2D component with the "Is Trigger" property checked on alongside a Rigidbody2D component with the "Body Type" property set to "Kinematic".
The colliders define the shape of the object's collision area. Without it the engine does not know how objects should collide with one another. The rigidbody component turns that object into a physics object. When two objects collide, at least one of them needs to have a Rigidbody component otherwise collisions won't occur. We put the rigidbody on the snake since it's the main object that can collide with everything else. Let me know if this helps at all.
@@Zigurous It is difficult for me to develop. Even when I watch the video and repeat something still comes out. I opened your Github and looked. What is the best way to study Unity?
I'm studying on video.
Becoming a Unity developer is a skill that needs to be practiced. As you put more time into it you will slowly increase your skills and knowledge. Videos are definitely one of the best ways to learn. Keep at it!
Really good Tutorial. Sadly, it is a bit frustrating that I followed along till the end to find out that the scoring and things like a GameOver & Win screen are not included in the Tutorial.
As a beginner, I now have to find another Tutorial and hope that the person uses a similar workflow to yours. Copying finished scripts from Github won't help me understand it. But I'm still thankfull you made this entire project public.
If the missing parts were included, it would've been perfect.
I spent over 30 minutes debugging my code when all that i messed up with my invoke repeating was my start method was manmade and wasnt Uppercase
A shorthand way of checking for the Null in the Action is to use the ?. notation;
this.destroyed?.Invoke();
why do we set the left edge to vector3.zero and not vector3.left?
Because we are using view-space coordinates which are defined in the range [0..1], with 0 being the left and 1 being the right. Similarly, if it were screen-space coordinates, it would be in the range [0..Screen.width]. In either case, 0 is the far left side.
Vector3.left = -1 in the x-axis
Ok thanks
Also I have an error saying that Projectile does not contain a definition for the system.action "destroyed"
nevermind i fixed it
Hello, how are you, there is a possibility that you please help me, it is seen that you are a good person. How can I get the player to fire automatically without pressing any keys?
Hello Zigurous!
First of all, thank you for this tutorial! It sure is interesting trying to understand from your video. 👍
I'm stuck at the part for the "Invader Movement 40:00". In the code I have:
"if (_direction = Vector3.right && invader.position.x >= (rightEdge.x - 1.0f)) {
AdvanceRow(); }"
But I got the error that "&&" can't be use with "Vector3" and "bool". I'm pretty sure I've done everyting like you so far, so I don't understand why that works for you and not for me. 🤔
Oh and I use ">=" because "≥" don't seems to work either.
Thank you for your good work and let me know if you have an idea regarding my problem. ^^'
When you write _direction = Vector3.right, you want to put two equal signs _direction == Vector3.right.
One equal sign is an assignment, two is a comparison.
@@Zigurous Thank you very much for your answer!! 🙏 I feel bad because watching your video again following your comment, I can see that there are indeed two equals (==). Sorry to bother you about this when it's 100% my fault, but thanks again for your help! >.
Where I can download all the Sprites Designssss?
github.com/zigurous/unity-space-invaders-tutorial
Assets/Sprites folder
How do i get the sprites i tried for half an hour
Use this download link and find the Sprites folder github.com/zigurous/unity-space-invaders-tutorial/archive/refs/heads/main.zip
Thank you!
Why are you using Vector3 in a 2D game when you could use Vector2?
I use Vector3 when setting Transform values because their underlying type is Vector3. That said, it's mainly out of habit because I spend more time in 3D environments, and I'm probably making it harder for myself (and others) by not using Vector2 more often for these 2D tutorials. It's something I'll try to be more conscious of going forward.
Hi :)
I have a problem:
ndexOutOfRangeException: Index was outside the bounds of the array.
Invaders.Awake () (at Assets/Scripts/Invaders.cs:22)
So this is the problematic line:
Invader invader = Instantiate(this.prefabs[row], this.transform);
I saw you had this problem too, but I didn't see how you fixed it. For me, assets do not move to the right through it. Help, please
If anyone has had a similar problem, it may be an easy issue to solve. I had a problem with editor layout. I updated Unity and the problem was gone. Now everything is ok. :)
When will u upload Pacman tutorial?
Hopefully very soon (within the next week or likely sooner). I am nearly done with creating the game itself and then I just need to record the video.
the accident is not your fault. wake up. - Jeff's Dad out.
HEy JEff's Dad you ever heard of DN
Deez Nuts!!!!! Jeffs Dad pwned
Unfortunately at 56:00 is where I run into a wall. Everything was going smoothly but then as soon as I disabled the player/laser collision, my player won't shoot.
Edit: Figured it out, make sure in project settings you are using Physics 2D and not just Physics! Leaving this comment up for any dummies like me.
using UnityEngine;
public class Invaders : MonoBehaviour
{
[Header("Invaders")]
public Invader[] prefabs = new Invader[5];
public AnimationCurve speed = new AnimationCurve();
public Vector3 direction { get; private set; } = Vector3.right;
public Vector3 initialPosition { get; private set; }
public System.Action killed;
public int AmountKilled { get; private set; }
public int AmountAlive => TotalAmount - AmountKilled;
public int TotalAmount => rows * columns;
public float PercentKilled => (float)AmountKilled / (float)TotalAmount;
[Header("Grid")]
public int rows = 5;
public int columns = 11;
[Header("Missiles")]
public Projectile missilePrefab;
public float missileSpawnRate = 1f;
private void Awake()
{
initialPosition = transform.position;
// Form the grid of invaders
for (int i = 0; i < rows; i++)
{
float width = 2f * (columns - 1);
float height = 2f * (rows - 1);
Vector2 centerOffset = new Vector2(-width * 0.5f, -height * 0.5f);
Vector3 rowPosition = new Vector3(centerOffset.x, (2f * i) + centerOffset.y, 0f);
for (int j = 0; j < columns; j++)
{
// Create an invader and parent it to this transform
Invader invader = Instantiate(prefabs[i], transform);
invader.killed += OnInvaderKilled;
// Calculate and set the position of the invader in the row
Vector3 position = rowPosition;
position.x += 2f * j;
invader.transform.localPosition = position;
}
}
}
private void Start()
{
InvokeRepeating(nameof(MissileAttack), missileSpawnRate, missileSpawnRate);
}
private void MissileAttack()
{
int amountAlive = AmountAlive;
// No missiles should spawn when no invaders are alive
if (amountAlive == 0) {
return;
}
foreach (Transform invader in transform)
{
// Any invaders that are killed cannot shoot missiles
if (!invader.gameObject.activeInHierarchy) {
continue;
}
// Random chance to spawn a missile based upon how many invaders are
// alive (the more invaders alive the lower the chance)
if (Random.value < (1f / (float)amountAlive))
{
Instantiate(missilePrefab, invader.position, Quaternion.identity);
break;
}
}
}
private void Update()
{
// Evaluate the speed of the invaders based on how many have been killed
float speed = this.speed.Evaluate(PercentKilled);
transform.position += direction * speed * Time.deltaTime;
// Transform the viewport to world coordinates so we can check when the
// invaders reach the edge of the screen
Vector3 leftEdge = Camera.main.ViewportToWorldPoint(Vector3.zero);
Vector3 rightEdge = Camera.main.ViewportToWorldPoint(Vector3.right);
// The invaders will advance to the next row after reaching the edge of
// the screen
foreach (Transform invader in transform)
{
// Skip any invaders that have been killed
if (!invader.gameObject.activeInHierarchy) {
continue;
}
// Check the left edge or right edge based on the current direction
if (direction == Vector3.right && invader.position.x >= (rightEdge.x - 1f))
{
AdvanceRow();
break;
}
else if (direction == Vector3.left && invader.position.x
amongus
you made a mistake the invaders are not able to kill the player because none of the have a rigidbody
just add rigidbody 2d to the invader base and it will automatically apply to the variants. also put body type as kinematic
@@arunabhrakshit That what I did, Im not a noob
@@kingsofplaystation5032 ok bro chill
I HAT YU
MEE TU,;
i need help im stuck on the animation code part and there arent any references above tyhe codes and i keep getting the error CSO246 and i dont know how to fix it so could someone please help and i also dont know what to put for ther greater than or equil to sign in the part where the code says this if (_animationFrame >this.animationSprites.length) {
_animationFrame = 0;
}