Forum

Coquitlam >> UN401 >> 12:40 pm - 1:40 pm

11/04/2018 - Jimmy Randa
Hello everyone!

Today we worked on creating health and score for our player, so our spaceship doesn’t instantly die when we hit something once, we can hit something 5 times before we die!

We came to our player script and added this code to the top, with all of our other variables:

public int health = 5;

This makes a variable for us called “health” and we start it off at 5. We’ll be using the variable to subtract from it as our spaceship hits things, and we’ll have to write some code that’ll say “If our health is 0 then we die”.

Next, down near the bottom of our player script, we added some code to know when our player’s box collider collided with another box collider in our game:

void OnCollisionEnter2D(Collision2D coll) {

}

Then we made 2 if statements, one to check for if we hit an enemy, and one to check for if we hit an asteroid. Inside of each of these, we need to subtract some health. So our code looked something like this:

void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == “Enemy”){
health -= 1;
Destroy(coll.gameObject);
}
if (coll.gameObject.tag == “Asteroid”){
health -= 1;
Destroy(coll.gameObject);
}

Lastly, inside of our Update we added:

If (health < 1) {
Destroy(gameObject);
}

This code monitors our health variable, and the moment it becomes less than one, we delete our player from the game.

Next for score we opened up our player script to create a new variable, named “score”

public int score = 0;

For our score, we will be adding to it as we destroy enemies, or asteroids, and we will be subtracting from it if we let enemies and asteroids past us, to the bottom of the screen.

We then opened up our laser script, and we added some new code that looked like:

void OnTriggerEnter2D(Collider2D coll){
if(coll.gameObject.tag == “Enemy”){
GameObject.Find(“Player”).GetComponent<Player>().score += 100
Destroy(coll.gameObject);
}
if(coll.gameObject.tag == “Asteroid”){
GameObject.Find(“Player”).GetComponent<Player>().score += 500
Destroy(coll.gameObject);
}
}

This adds some score to our player script’s variable. We also used the if statements to know when we hit an asteroid, or when we hit an enemy so that we could add different amounts of score.

Next, we needed to subtract score if we let them past our screen.

We added this next chunk of code to both our asteroid script, and our enemy script:

void OnBecameInvisible(){
GameObject.Find(“Player”).GetComponent<Player>().score -= 100
Destroy(gameobject);
}

Lastly, we made the GUI to display our health and score to the player:

Come to your Unity hierarchy, and right click, select “UI” and click “Canvas”. Canvas should now be in your hierarchy, along with EventSystem. Make sure you don’t delete the EventSystem as it’s important for the GUI to work!

Then we right clicked on our Canvas, Clicked “UI”, Clicked “Text”.

This makes a text box in our GUI. We changed what the text said to “Health: ”, and we resized it a bit, and moved it up in the top left corner.

In our inspector, we changed the anchor to the top left of the screen, and then we checked the box called “Best Fit” near the bottom. The anchor and best fit options make sure that our GUI is the right size no matter how big or small our screens are, and also in the right position.

Duplicate your text, move it to the top right and change what it says to “Score: ”. Also change the anchor to top right.

At this point, I think it’s a good idea to rename our Text in the hierarchy to something more specific. Name the Score one “Score” and the Health one “Health”.

Now let’s go back to our player script and add some code that will update our texts with the numbers in our variables we made from previous classes.

We need to make 2 variables that will hold those text boxes we made, but in order to do that we need to import some new code into our script.

Using UnityEngine.UI

Our script editor doesn’t come with everything automatically, to save space, so if we want to use GUI related code we have to do what’s called “importing” it with that line of code. So now we can make these two variables:

public Text healthText;
public Text scoreText;

And lastly, inside of update we simply need to add somewhere:

healthText.text = health;
scoreText.text = score;

Next class we’ll work on explosions and particle effects!


11/18/2018 - Jimmy Randa
Hi everyone!

Today we worked on making a new enemy in our game, one who shoots back at us.

We used a whole bunch of things we’ve learned in previous classes to get our enemy going, as review, so hopefully it wasn’t difficult to follow.

First, we got a new image and dragged it into our scene. Rename it, give it a rigidbody2D, and a box collider. Tag it as our “enemy” tag.

Create a prefab of this new enemy, by dragging it from the hierarchy into the prefabs folder.

We created a new script named “shootenemy”. Inside it we needed to make it move down first, so inside of update we added:

transform.Translate(Vector2.down * speed * Time.deltaTime);

We are using “speed” in the above line of code, so of course we need to make sure we make a speed variable.

Next, we used InvokeRepeating and Instantiate to make it shoot. Create a enemyLaser variable at the top of your script to use in the instantiate.

We create a shoot function that looked like this:

void Shoot(){
Instantiate(enemyLaser, transform.position, Quaternion.identity);
}

Then, inside of start we need to turn on the InvokeRepeating, so we added this inside of start:

InvokeRepeating(“Shoot”, 1f, 2f);

Lastly, we need to make a new laser prefab, one specific for our enemy, because the one we made for our player goes up and our enemy needs to shoot down at us!

We created a new laser in our scene, turned it into a new prefab, then created a new script with one simple line of code to make it move down:

transform.Translate(Vector2.down * 25 * Time.deltaTime);

Next class we’ll look at making our player respawn when we get destroyed, something like a “Try again” button that also displays your score!


10/14/2018 - Jimmy Randa
Hello everyone!

In this class, we learned about tagging, finished up the ability to hit enemies, lasers hitting enemies, and we made our enemies move down.

We need to make sure our game objects are tagged. If you click on your enemy in the hierarchy, then look at the inspector window, under the name there should be a Tag option. Click on the tag box, select Add Tag and a new window will pop up. Click the + sign and type in Enemy and click save. Also make one for laser. We can now click on the game objects in the hierarchy, and select the tags where it's appropriate. Our player should be tagged player, our enemy should be tagged Enemy, and our laser should be tagged laser

We came to our laser in the hierarchy and added another box collider 2D to it. Check Is Trigger once again. You may notice a green box is now around your projectile, and it may be bigger than the projectile. If that's the case, we click on the Edit collider button in the inspector window, and then resize the green box to match the size of our projectile image.

Using the tags we made earlier, we can search for specific things we want to destroy! This is useful so we don’t accidentally destroy our player when he gets hit by his own laser.

Let’s open up our Player script once again, and make a small change so our code looks like:

void OnTriggerEnter2D(Collider2D coll) {
if(coll.gameObject.tag == “Enemy”){
Destroy(coll.gameObject);
Destroy(gameObject);
}
}

Lastly, we made our enemies move down towards us. We made a new script called Enemy, and opened it up.

Just like before, we created a speed variable, then inside the update function we added code that looked like:

public class Enemy : MonoBehaviour {
public float speed = 2f;

void Start () {

}

void Update () {
transform.Translate(Vector2.down * speed * Time.deltaTime);
}
}


Save your script and try testing your game! You enemies should now move downwards.

Lastly, we made it so that if a projectile hits an enemy, both the projectile and enemy get destroyed. We did this by using a built in function unity has, to let us know when two box colliders touch. Remember how we added the box collider to the projectile, and the enemy spaceship?

In our enemy script, below our update function and above the very last curly bracket, we added code that looked like:

void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == “Projectile”)
{
Destroy(gameObject);
Destroy(coll.gameObject);
}
}

Notice how I'm looking for the Projectile tag we made earlier! This has to match exactly, so if your tag is lowercase then you need to type lowercase here too. This code is saying that if the tag of the object that touched is tagged as Projectile, then we Destroy both the projectile, and the enemy spaceship.

Next class we'll work on spawning infinite enemies!


10/21/2018 - Jimmy Randa
Hi everyone!

This week in class we got our enemy spawner to work!

We started off by coming to the hierarchy and right clicking to create a new empty. We named it “Spawner” and moved it just above the view of our camera in the scene.

The location of where we move it will be the height (Y) of where the enemies spawn. We put it just above the camera so the player can’t see enemies just POP in to the screen, if they spawn above they will have to slowly move down into the screen which looks nicer!

We then created a new script, named SpawnerScript. Here is where we'll code our enemies, and later asteroids to spawn infinitely! We opened it up and started by adding a variable at the top, just under the class line. It looked like:

public GameObject enemy;

This sets up our script so that it knows exactly what an enemy is! We’ll be putting our enemy prefab into this variable. Now, we need to make a new functions to spawn our object (our enemy) for us. Below update, we typed out:

void SpawnEnemy()
{

}

This is where we'll put our code to spawn our enemies. We made use of the Random.Range function. Since we don't want our enemies to always go in the same spot every time, we use this to get a random number for our X value.

Inside of our SpawnEnemy function we added:

Vector2 spawnPosition = new Vector2(Random.Range(-8f, 8f), transform.position.y);

So now we have a variable called spawnPosition and it has a random X value, and a Y value of our spawner up above the camera.

Now we need to use this spawnPosition in spawning the enemy, so we used Instantiate once again. Instantiate lets us make a copy of our prefab, and remember, our prefabs are like a master copy that we can keep on copying.

So just below the spawnPosition line of code, we added:

Instantiate(enemy, spawnPosition, Quaternion.Identity);
We instantiate our enemy gameobject, give it our spawn position, and tell it what rotation to spawn at Quaternion.Identity, which just means no rotation.

Lastly, we need to be able to run these functions infinitely. Inside of the Start function, we made use of InvokeRepeating. This lets us call our newly made functions repeatedly, and give it a time to wait in between repeats, and it'll just go on forever.

void Start () {
InvokeRepeating(SpawnEnemy, 2f, 2f);
InvokeRepeating(SpawnAsteroid, 1f, 5f);
}

Now we just need to go back into unity, attach the SpawnerScript to our Spawner gameobject, and drag our prefabs into the appropriate empty boxes in the script component.

Try your game out! It should be spawning both asteroids and enemy spaceships and they should be coming down towards you!

Next week we’ll apply what we learned by adding asteroids to our game!


10/28/2018 - Jimmy Randa
Hi everyone!

Today was a work day to implement an asteroid into our game using similar techniques as we used for our enemy space ship! Everyone got a chance to try out what we’ve been learning themselves.

There were 3 goals for our asteroid:

1. Make it move down
2. Destroyable by your player’s laser!
3. Infinite spawning with our spawner

Everyone managed to complete their asteroid by the end of class! Great job!

Next week we’ll be working with the particle system in unity to create explosions.

Bonus: Can you make the asteroids come down at a diagonal instead of straight down?


09/09/2018 - Jimmy Randa
Hello everyone!

My name is Jim and I'm your instructor for Unity 301 this semester. I'll be using this page to post summaries of what we learned in class, it'll include all the scripts and code we went over too. I'll also be posting optional things to do at home!

Before we begin, I’d like to remind everyone to make sure you’re bringing a USB drive to class, so we can save your game after every lesson, and you can bring it home and show it to your parents or continue working on it!

Much like how an engine powers a car, we're using Unity to power our games. We use a game engine because it comes with pre-made and complicated functions that we can easily put into our games! So we won't have to go do all the complex stuff like physics ourselves!

In our first class we learned our way around Unity:

The hierarchy window on the left contains everything that's in our scene – it keeps track of everything we put into our game, also known as “Game Objects”.

The scene view in the middle is where we can place and move around objects in our game.

The game tab shows us what our game camera can see! Also what our player will see when playing our game!

The inspector tab shows us all the properties and settings of our selected game object.

The asset window at the bottom contains all our assets that we use throughout our game. These assets include things like images (sprites), scripts, scenes, animations, and many more things! Anything that’s in this window means that we can put it into our game. Just remember that if something is in the assets window, it does not necessarily mean it’s in our game yet! Think of it as it’s “waiting to be used”. We have to put it into our scene / hierarchy for it to be in our game!

Lastly, the console tab shows us errors in our code, or things we print from code!

We can move all of these windows however we’d like by dragging them around and resizing them. To reset your Unity layout back to default, click on “Window” at the top left, hover over “Layouts”, and select “Revert Factory Settings”

We started off by making folders in the asset window. It’s important to stay organized in our project because as we progress we’ll have plenty of things in our assets. We made three folders labelled Scenes, Scripts, and Sprites. Remember, right click in the asset window and selected create - folder. Then we saved our project by going to the top left of unity and clicking “file” and clicking “save scene as” and we selected our scenes folder. You can name your scene whatever you’d like – mine was named “Level1”.
Then we went on Google images to find our first asset! Something to be our player, you can use anything you’d like, but I’m sticking with the space theme, so I’m looking for a space ship. We saved the image and then dragged and dropped it into our asset window, sprites folder on unity.

Once the spaceship image is in your assets window, we can drag it into our scene and make our first Game Object! Click and drag the spaceship from assets into the scene view.

You'll notice there's something new in the hierarchy window, our spaceship is now a Game Object. Remember, the hierarchy keeps track of our Game Objects, and anything in our scene is a Game Object. Click on it in the hierarchy and notice the inspector window on the right changes – we can see all of the properties that come with our space ship.

At the top of the inspector window, there's a box for our Game Object’s name that we changed to “Player”. It’s good to name your Game Objects after what they represent to stay organized!

We then learned about the Game Object manipulation tools. At the top left of Unity there were 5 tools. We can click on them, or use hotkeys to access them. Once you select your Player in the hierarchy you can then use:

Q to use the pan tool, pans the screen. Useful for moving around our really big levels!

W for the move tool, lets us move the selected Game Object.

E allows us to rotate Game Object.

R is the scale tool, for resizing Game Objects bigger or smaller.

T allows us to move our objects freely and scale our Game Object.

That was everything for our first lesson. I encourage you to try what we went over in class at home! Also, you could get a head start by finding some images / sprites you want to put into your game. We need images for each of these objects in our game: A player space ship, enemy space ship, asteroid, an explosion, a background, a laser we can shoot, and something to use as a particle like a star.


09/16/2018 - Jimmy Randa
Welcome back everyone!

Our second class of UN301 was an introduction to scripting!

We went over a few things, like the difference between Start() and Update(), curly brackets, semi-colons, and if statements.

To create a new script, come to your assets window at the bottom, come into your scripts folder, and right click, Create, C# Script. Once you click the C# Script button it will pop up in the assets window, and it’ll let you type in a name.

Be careful, once you give your script a name you cannot change it easily. If you do accidentally give it a wrong name, it’d be better to delete it and create a new one before we start coding! Also, your script names cannot contain spaces! We named our script “Player”, and then double clicked on it to open it up.

In our script we see 2 important pieces of code that come with every new script. Start() and Update(). The start function runs once when our game starts. This is useful for code that only needs to be ran once at the beginning of your game.

The update section repeats very fast - More specifically 60 times a second, because Unity runs at 60 frames per second. This is useful for when you want to constantly check for something happening in your game!

To demonstrate this, we wrote our first line of code in the start function, and we wrote a simple print to our console. This looked like:

void Start () {
print(“Hello”);
}

Make sure you save your script so that Unity can see its changes!

Go back to unity, and remember, just because our script is in our assets window does not necessarily mean it’s in our game yet! So we’ll have to drag it into our game.

Click and drag your player script from the assets on top of your player Game Object in the hierarchy! If you click on your player in the hierarchy to select it and bring up its properties in the inspector, you should notice a new box pops up on the inspector of the player, labelled “Player (Script)”. Click the play button at the top middle of your screen to play your game. If you click on the console button next to your asset window button, you should notice it printed “Hello” once!

We can stop playing our game by clicking the play button again at the top.

If we come back to our script and delete our line of code:

print(“Hello”);

And then type it inside our Update(), so it looks like this:

void Update () {
print(“Hello”);
}

We should get something else happening when we play our game. Remember to save your script, and pay attention to the console again once playing your game. It prints it very fast and many times a second.

Two important things we went over were the curly brackets and the semi-colon. Every statement of code we write will need a semi-colon “;”, for example our print line. If you accidentally forget one, your code won’t work, so if you have an error be sure to double check your semi-colons.

Every statement that will have a chunk of code inside it, will use curly brackets. For example our Start() and Update() have a pair of curly brackets “{ }” one opening and one closing. Things like functions, and if statements will always need a pair of curly brackets. Again, if you accidentally miss one and get an error, be sure to double check your curly brackets!

Lastly we went over “if statements”. An “if statement” in programming is basically saying you’ll run the code inside, if the condition is true. For example in real life we might say: “if it’s sunny today, I’ll go play soccer outside”. You’ll only go play soccer if it’s sunny. In programming this looks like:

If(Our condition inside these brackets) {
Code inside the curly brackets;
}

That concludes our introduction to scripting! Try to write a story using prints and then see it pop up in your game’s console.


09/23/2018 - Jimmy Randa
Hey everyone!

Jim here. Welcome back to our third class. Today we got our character moving in our game.

We opened up our Player script and started typing a few lines of code inside of Update() to get our movement going. They looked like this:

void Update(){
if(Input.GetKey(KeyCode.W)){
transform.Translate(Vector2.up * Time.deltaTime);
}
}

Our if statement is waiting for our player to press the W key. If the W key is pressed, then we move our player up. Transform is basically another word for our player’s position, so we translate our player’s position by “up”. This code is good for just one direction though, so we then copied and pasted it for the 3 other directions and changed the key and the direction!

void Update(){
if(Input.GetKey(KeyCode.W)){
transform.Translate(Vector2.up * Time.deltaTime);
}
if(Input.GetKey(KeyCode.A)){
transform.Translate(Vector2.left * Time.deltaTime);
}
if(Input.GetKey(KeyCode.S)){
transform.Translate(Vector2.down * Time.deltaTime);
}
if(Input.GetKey(KeyCode.D)){
transform.Translate(Vector2.right * Time.deltaTime);
}
}

Something to keep in mind is that when you’re writing your code, you need to make sure you spelling and capitalizations are all matching perfectly. Otherwise, unfortunately Unity will get confused.

Now save your script and try playing your game, you should be able to move in every direction.

It starts off really slow, so we can increase the speed with a variable. A variable is like a placeholder for future information, you could let it store any information you’d like. In this case we’re going to make a “speed” variable, and give it a number to store to go that much faster by.

At the top of our script, below where it says “public class” we added a variable like so:

public float speed = 5f;

After making our variable, we can now use it to make our ship move faster when we press keys. Come down to your movement code and we’ll modify the lines that start with transform.Translate like so:

transform.Translate(Vector2.up * speed * Time.deltaTime);

transform.Translate(Vector2.left * speed * Time.deltaTime);

transform.Translate(Vector2.down * speed * Time.deltaTime);

transform.Translate(Vector2.right * speed * Time.deltaTime);

If we save our script now, and go back to Unity and play our game, we’ll see that our spaceship moves faster.

One thing that’s great about using the word “public” behind the variable is that we can now directly edit the variable from Unity. So if you click on your player in the hierarchy, look in the inspector window, find the “player (Script)” box, and you should see something labelled “speed 5”. You can change the 5 number to faster or slower to your liking, and Unity will automatically change it in your script. So we don’t have to open it back up if we want to move slower or faster. You can also change this while the game is playing to test your changes live!

The last thing we learned about was prefabs, and just keep in mind that all prefabs are, are just a master copy of a Game Object we’d like to clone many times. So for example, for our laser, whenever the player wants to shoot we’ll be cloning a new laser for each time he shoots. So these clones need to come from a master copy – a prefab.

Next class we’ll be learning how to shoot lasers and get them to move! We’ll also learn how to get them to collide with our enemies.

Some things you can try at home are: Try making it so that when you press a key, your speed gets changed to either faster or slower. Try making a second player with a different set of keys you can move around with! Try making a different spaceship that only moves down automatically.


09/30/2018 - Jimmy Randa
Hi all!

Today we added some new features to our game, the ability to shoot lasers, and hit enemy spaceships.

The first thing we needed to do was to create a prefab (master copy) of our laser that we can clone each time our player wants to shoot. We put a laser image from our assets into our scene, turning it into a Game Object. You should see your laser Game Object in the hierarchy now.

In our assets window, we made a folder named “prefabs” to stay organized. Now all we have to do is drag and drop our laser from the hierarchy into our prefabs folder. Now we have a prefab of our laser.
We then opened up our code, and we started by adding a variable to the top to store our prefab:

public GameObject laser;

Then, below our movement code, still inside of the Update curly brackets, we need to add a check for if the player is pressing the space button, which looked like this:

If(Input.GetKey(KeyCode.Space)){

}

Then inside we added the line of code that clones our prefab! We used a function called Instantiate() which basically means to create something, to clone something. We needed to tell it what to create/clone by putting out laser variable inside of the brackets, then we need to tell it what position to create it at. This looked like:

If(Input.GetKeyDown(KeyCode.Space)){
Instantiate(laser, transform.postion, Quaternion.Identity);
}

Make sure you save, and now we need to head back to unity, click on our player Game Object in the hierarchy. Find the script box in the inspector window again, and we should now see both “speed” from last class, and our new “laser” that we just added. If it isn’t showing up you may have errors in your script, so double check to make sure everything is good, or maybe you forgot to save.

We need to drag our laser prefab from assets window into that new laser variable that popped up. Once you do this, try playing your game and pressing space. You should now have the ability to create lasers! But they don’t move yet!

To get our laser to move, we need to create a new script in our scripts folder. Name this one “laser”. Open it up, and inside it we need to add one line of code inside of Update:

void Update(){
transform.Translate(Vector2.up * 25 * Time.deltaTime);
}

This will make our lasers move up constantly (Think back to print(“Hello”), how update will constantly repeat and move our laser up and up). The number 25 is just in place of our speed variable, instead of making a variable for it we just simply put the number in. It doesn’t have to be 25 but your laser should probably be fast, so pick a speed you like!

The last thing we did was start on enemies in our game. Find an image you’d like to use for your enemy space ship, and drag it into your scene to create it as a Game Object.

We talked about Rigid Bodies, which add physics to our Game Objects, and then we talked about Box Colliders, which allow our Game Objects to collide with each other.

We need to make sure we add a RigidBody2D to both our player and our enemy Game Objects. Select one in the hierarchy, and at the bottom of the inspector window there’s a button “Add Component”. Click it and search for RigidBody2D. Do this for both space ships.

Now after doing this, we noticed that our space ships falls down after we play, because our space ship now has physics, which makes it fall down. We need to disable the vertical (falling) physics in our game, so come to the top left of Unity, click on Edit, go down to “Project Settings” and find “Physics 2D”. Once you click on this your inspector window will change, and we need to change a box for Gravity Y at the top to 0. We should no longer fall down when we play our game.

We need a way to be able to detect when our space ships and lasers hit each other. We're going to start by clicking on the enemy in the hierarchy, and add Component again. We want to type “box” and double click on the Box Collider 2D.

The newly added box collider should pop up in the inspector window, and we should be able to see its properties. It's important that we check the box labelled Is Trigger. We need to add the box collider 2d to the player now as well, make sure you check Is Trigger.

If you accidentally add a component you don't want, you can delete it by clicking on the wheel at the top right of the component, and clicking Remove Component.

Once that is done, we can now write the code to see when our player hits the enemy! Open up your player script, and we'll add the following code. Make sure that it's ABOVE the very last curly bracket, but BELOW the curly bracket that ends your update function! Otherwise the script will be confused and it'll give you errors.

void OnTriggerEnter2D(Collider2D coll) {
print(“I hit something!”);
Destroy(coll.gameObject);
}

That was everything for today’s class! See you all next week!