Skip to content
Cawd Logo GAWD
  • Home
  • About
  • Assignments
  • Resources
  • Contact

Wednesday, April 8th

Wednesday, April 8th

Class hours: 10:05 – 2:45
Mr. Bohmann | wbohmann@ewsd.org

10:05 Today’s Notes & Attendance

  • LipSync Battle at 12:15 – be ready with your project
  • NTHS returners – practice on Thursday (10:45 – Lunch) – that will impact your Skills work so talk with your partner(s)

10:10 Unity Logic

Flow Control Continued….

image of rocket landing

Let’s continue working with the concept of flow control and logic with the Lunar Lander we made yesterday.

You can use any logical expression inside an if() or else if() statement. So, you can ask complex questions like “is score greater than 100 AND is playerHealth less than or equal to 0?” In our working example yesterday we checked to see the velocity at which the lander hit the platform.

 if (currentVelocity > 5)
 {
     shipStatus.text = "Crash";
 }
 else if (currentVelocity > 4)
 {
     shipStatus.text = "Easy, Cowbody";
 }
 else if (currentVelocity > 3)
 {
     shipStatus.text = "Improving";
 }
 else
 {
     shipStatus.text = "Nicely Done Captain";
 }

You can also ask very simple questions such as “is shipStatus equal to 1″? In fact, you may frequently want to ask a series of “equal to” questions about one variable or expression and take some different action with each result.

if (shipStatus == 1)
{
   Debug.Log("All Systems Green");
}
else if (shipStatus == 2)
{
   Debug.Log("Yellow Alert");
}
else if (shipStatus == 3)
{
   Debug.Log("Getting toasty in here");
}
else
{
   Debug.Log("Head for the life pods!");
}

While this if / else-if / else chain will work fine, C# provides a cleaner way to test if one variable or expression is “equal to” many different values.

The if() statement is not the only way to control your program flow. The switch has decision-making power similar to an if / else-if / else chain. Switch statements are useful when you want to compare one value against a series of other values and execute different code on each “equal to” match.

The “switch” statement

The switch() statement will accept one variable or expression to test, and then allow you to write different blocks of code for each possible value or “case“. Let’s rewrite our example using the switch statement.

switch (shipStatus)
{
   case 1:
      messageText.text = "All Systems Green";
      break;
   case 2:
      messageText.text = "Yellow Alert";
      break;
   case 3:
      messageText.text = "Getting Toasty in Here";
      break;
   default:
      messageText.text = "Head for the Life-pods!";
      break;
}

What’s going on here? The switch statement begins with the switch keyword, followed by an expression in parentheses. The expression must evaluate to an integer number such as byte, int or long, or a char or string. In our example, we simply used the variable shipStatus, which has been declared elsewhere as some integer type. Important – You cannot switch on a fractional data type such as a float.

Let’s open the Lunar Lander project and see how this works.

The entire body of the switch statement is contained within the opening and closing curly braces.

Within the switch, curly braces are one or more case statements. A case represents one possible value of the switch expression and the code you want to run when the expression is “equal to” that value.

You can add as many case statements as you like; one for each value you want to check. You can also add a default case at the very end. This is similar to the else statement after an if() expression. The default case will be executed if no other case value matches (see above code example for a default case)

switch (health)
        {
            case 3:
                Debug.Log("Your Health is Excellent");
                break;
            case 2:
                Debug.Log("Your Health is declining");
                break;
            case 1:
                Debug.Log("Your are almost finished!");
                break;
            case 0:
                Debug.Log("You are dead");
                break;

        }

Now that we have seen this done. Let’s look at the if / else statements we made in our Lunar Lander and clean them up with a switch statement. Remember when I said we cannot use floats?. A float is a (fractional) value, and you can’t use fractional data types directly in a switch statement.

So, the first thing you’ll do is convert the float to an integer data type. You can cast (convert) a fractional data type to an integer type by placing the new data type in parentheses in front of the fractional value.

// explicitly cast fractional value to integer
 int shipLandingstatus = (int)relativeVelocity; // converts float to int & now we can use in switch statement

10:50 Break

11:00 Using Instantiate() to Create PreFabs

We’ve seen how we can write code to destroy gameObjects.

void OnCollisionEnter2D(Collision2D otherObject)
{
Destroy (otherObject.gameObject);
}

The Destroy() logic can be placed anywhere in your scripts, so long as you have a reference to the target object. You might remove objects in the OnCollisionEnter2D() and OnTriggerEnter2D() functions, or from the Update() function or in some other function – whatever makes sense to your game.

If we put that bit of code above on your Lunar Lander, it would destroy any game object it collides with.

The Destroy() function can take a second parameter that allows you to delay the effect. You can pass in a number of seconds such as 0.5 or 2.0 and the object will not actually be destroyed until that much time passes.

void OnCollisionEnter2D(Collision2D otherObject)
{
Destroy (otherObject.gameObject, 1.0F);
}

We can also use code to create gameObjects too. This is really handy with PreFabs, spawning enemies, handling bullets managing random power-ups – I could go on. Let’s start basic then add some heavy lifting:

  1. Open your Lunar Lander game.
  2. Add an asteroid sprite to the hierarchy
    1. Add circle collider 2D
    2. If you have a rotation script, pop that on as well
    3. Drag to your PreFabs folder – you now have a prefab
    4. Delete your PreFab from the hierarchy
  3. Open your LunarLander Script and
  4. Create a Public GameObject asteroidPreFab variable
  5. Populate that new variable slot with your PreFab from the PreFabs folder
  6. In the void Start method of your LunarLander add in the following line of code
// create a variable that is public
public GameObject asteroidPreFab;


   void Start () 
   {
      Instantiate(asteroidPreFab); // create a new copy of the prefab
   }

We have chosen to call Instantiate() in the Start() function of this script, because we want the asteroid to be created right away when the game starts. But, you can call Instantiate() from anywhere that makes sense for your game! For example, if you are firing bullets from a gun, you might call Instantiate() from inside the Update() function when you detect the trigger key.

What happens if we run this script – where do the Asteroids go?

public GameObject asteroidPreFab;


   void Start () 
   {
      Instantiate(asteroidPreFab); // create a new copy of the prefab
      Instantiate(asteroidPreFab); //copy 2
      Instantiate(asteroidPreFab); // copy 3
      Instantiate(asteroidPreFab); // copy 4
      Instantiate(asteroidPreFab); // copy 5
      Instantiate(asteroidPreFab); // copy 6
   }

You can actually call Instantiate() with one or more additional parameters to configure the cloned object. This version lets us add a new position and rotation to the new object.

Instantiate (asteroidPreFab, new Vector3(4.0F,2.0F,0), Quaternion.identity); 

The Vector3 parameter contains the X, Y, and Z coordinates of the new object in world units. You can get a good sense of the X and Y units by looking at the grid lines within the camera rectangle on the scene. Each grid line is 1 world unit, so if your camera is showing 5 boxes vertically and 8.5 horizontally in every direction from the center.

ProTip: You can toggle grid lines on and off (look for the Y icon near the grid icon at the top of Scene)

The third parameter is a Quaternion that represents the rotation angles in the X, Y, and Z directions. A Quaternion is actually a complex object that you don’t want to try and modify yourself. Fortunately, if you don’t want your new object to be rotated, you can pass in the value Quaternion.identity, and the object will be created with no rotation.

11:35 Lunch

tacos

12:15 Lip Sync Battle

When we finish lip sync battle, jump into your Unity Environmental Design project or your Skills/Design work. There is a drop box in Google Classroom for your LipSync. Check your audio!

1:00 Afternoon Break (15 minutes)

1:15 Dailies

1:20 Independent Reading

book covers

1:45 Dismissal

GAWD Instructors:

Matt Cronin

Will Bohmann

Instragram Facebook Twitter

A little about GAWD:

Serving high school students interested in Gaming, Animation, and Web Development in North Western Vermont.

Students continue at:

University of Vermont Ringling School of Art and Design Northeastern University Rochester Institute of Technology Concordia University

Students find careers at:

Dealer.com Union Street Media Rovers North Prudential Investments DockYard
Navigate to top of page