Learning Objectives

In this lesson, we are going to use our new knowledge of arrays to clean up our code, eventually letting us work toward adding spatial sound. We often need to understand concepts like arrays, however, to begin to understand how sound works in the computer. Thus in this tutorial, we are first going to focus on converting our code to use arrays.

You will:

  1. Learn about refactoring, the process of changing around existing code
  2. Learn about looping using repeat
  3. Learn about spatial sound

Refactor Existing Code to Use Arrays (10 Minutes)

The items for our quest are stored so far in individual variables. We want to change this to clean up our code. As a first step, we are going to declare an Array, like so:

For 2D use:

Array<Item2D> goodItems

For 3D use:

Array<Item3D> goodItems

These declarations tells us that we want an array and the type is either Item2D or Item3D, which is what the Scene Editor stores. By making this declaration, we can then fill the array and manipulate these items.

Repeat (15 minutes)

One big advantage of data structures like arrays is that we can loop over them, which means we can ask the computer to do the same code on each one of them. In essence, we tell our program we want to Hide a bunch of items, instead of calling Hide on each one individually. This reduces code duplication and requires we learn about repeat.

Find the Closest Item to the Player (10 minutes)

In computer science, we often create what are called algorithms, which are essentially steps for solving problems. Using our distance equation we used in a previous lesson, or a new one, use a loop to figure out which of the items we are looking for is closest to the player. At the end of this part, your algorithm should output the name of the closest item to the console. We want to give a player a way to find an item, so make the F key trigger this operation. We need to use repeat and our array to solve this problem.

Investigate Spatialized Sound (10 minutes)

We now have a way to find the item closest to us. For this final section, investigate the Audio Class. Try to figure out as a group how you can use this information to use sound such that it tells the player if they are getting closer, or further away from, the closest item.

Next Tutorial

In the next tutorial, we will discuss Trigger Recorded Voice Over for Quests, which describes trigger recorded voice overs..