Chapter 5
IN THIS CHAPTER
Finding and setting position and direction
Adding randomness to position and direction
Moving and turning an object
Coding an asteroid destroyer game
This chapter helps you acquire the skills you need to perform geometry tasks when programming. Specifically, you find out how to position an object and set it in motion onscreen. If your kid is writing code to create an animated game or build a model, then placing objects in different positions and moving them around is a key skill.
Here, you and your coder discover the basics of working with x and y coordinates, as well as how to point an object in any direction. We also show you how to make objects move, set the speed of objects, code some practical programs that include using randomness to scatter many objects into different positions, and determine whether two objects collide.
Finding out “where you are” is fundamental to creating any kind of program that involves objects onscreen. In the real world, you use a wide range of descriptions to indicate where you’re located (see Figure 5-1).
Coding uses systems and rules similar to mathematics to determine position. These rules identify where you are in two directions: the x-direction and the y-direction.
The x-direction and the y-direction are each specified by a number. The two numbers are written together to form an (x, y) coordinate pair, or coordinates, such as (4, 20) or (100, 200).
The coordinate (0, 0) may identify a different position from one programming language to another (see Figure 5-2). When your coder is working in Scratch, (0, 0) the location is the center of the stage. This means that there are coordinates with negative values for x positions to the left of (0, 0), and coordinates with negative values for y positions lower than (0, 0). In JavaScript, (0, 0) is the location at the top-left corner of the screen. As you move down the screen in Scratch, y values decrease, but as you move down the screen in JavaScript, y values increase.
One way you can understand the big picture of a computer program is to act it out, unplugged. Try playing a classic game of Battleship! (See Figure 5-3). The game, played by you and your young coder, involves each player hiding plastic ships of various sizes on a game board. Alternatively, you can draw a game board on a piece of paper, as a 10 by 10 grid, and then draw ships on the board. Create a variety of ship sizes from two to five grid blocks in size. Label each ship location by its horizontal coordinate, a letter of the alphabet (A through J); and its vertical coordinate, a number (1 through 10). Take turns attempting to “hit” an opponent ship by calling out a location on the game board. The goal is to hit and sink all enemy ships. Again, a key understanding of Battleship is that you can represent position on the two-dimensional game board by a coordinate pair, such a A-5, or H-10.
Another fun way to explore coordinates is to play a city scavenger hunt by providing your kid with a number pair that represents the geolocation — the latitude and longitude in degrees — of a famous city. (See Figure 5-4.) You can find these geolocations on the Internet in advance. Then provide the list of coordinate pairs to students and invite them to use a traditional map, a globe, or Google Maps to locate the cities. For example, type 36.17° N, 115.14° W into Google Maps to reveal Las Vegas!
Setting the position of an object means assigning it coordinates to put it in a specific place onscreen. Finding the position of an object means identifying its coordinates to know where it’s located.
While each programming language uses its own structure for setting and finding coordinates, a typical pseudocode expression you may write to set the position of an object looks like this:
setx x-coordinate
sety y-coordinate
Or
setposition (x-coordinate, y-coordinate)
To find the current position of an object, you can write pseudocode for each separate coordinate: x-position
for the x-coordinate of the object, and y-position
for the y-coordinate of the object. You can also write position
to describe the object position as a coordinate pair.
To set the x-coordinate of an object in Scratch, use the set x to
number
command in the Motion category (see Figure 5-5). The minimum value of the x-coordinate ranges is -240, and the maximum value is 240.
To set the y-coordinate of an object in Scratch, use the set y to
number
command in the Motion category (see Figure 5-6). The minimum value of the y-coordinate ranges is -180, and the maximum value is 180.
To set both the x-coordinate and y-coordinate of an object in Scratch, use the go to x:
number
y:
number
command in the Motion category (see Figure 5-7). The range of the x-coordinate value is -240 to 240, and the range of the y-coordinate value is -180 to 180.
To find the x-coordinate of an object in Scratch, use the x position
command in the Motion category. To find the y-coordinate of an object in Scratch, use the y position
command in the Motion category. You and your coder can use these commands in your programs when you need to write commands that require information about an object's position.
As you code, sometimes you want to position an object (sprite) onscreen and then get its coordinates. You can do this for any sprite using either of these methods (see Figure 5-9):
x position
command and the y position
command in the Motion category to show these values onscreen.In both methods, the coordinates of Scratch Cat are (60, -18).
To set both the x-coordinate and y-coordinate of an object in JavaScript, identify the object you want to position, and then use the setPosition
command.
Here are the steps for how to position an image of a mouse onscreen in the Code.org App Lab, using JavaScript.
In the Workspace, select Image ⇒ Choose.
The Choose Assets dialog box opens.
Select the file you want, and then click the Choose button.
The uploaded file appears in the dialog box as shown in Figure 5-10. The name of the uploaded image file shown here is mouse.png
.
image("character", "mouse.png");
setPosition("character", 160, 225, 100, 100);
Here is what these commands do: The first command creates an image reference identification, character
, and links the file, mouse.png
, to this identification. The second command displays the image in character
according to four quantities: the x-coordinate of the object, the y-coordinate of the object, the width of the object in pixels, and the height of the object in pixels.
Figure 5-11 shows the mouse positioned at the coordinates (160, 225), which is the exact center of the screen. You can see that the mouse is positioned by its upper-left corner where the tip of its tail is located. The mouse has a width of 100 pixels and a height of 100 pixels.
To find the x-coordinate of an object in JavaScript, use the getXPosition("character")
; command where character
is the identification reference of the object. To find the y-coordinate of an object in JavaScript, use the getYPosition("character")
; command where character
is the identification reference of the object.
You and your coder can write the following code to find and display onscreen the coordinates of an object named character
. This assumes you have uploaded an image file and assigned it to the reference identification, character
. Type this code in the App Lab program workspace.
var x = getXPosition("character");
var y = getYPosition("character");
textLabel("xcor");
textLabel("ycor");
setText("xcor", "x-coordinate is " + x);
setText("ycor", "y-coordinate is " + y);
Here is how this code works:
var x
variable gets the x position and the var y
variable gets the y position of the object.textLabel
commands create locations onscreen, called xcor
and ycor
, to display information.setText
command displays a value in a text label. The value of x
displays in the xcor
label and the value of y
displays in the ycor
label.Figure 5-12 shows the output of this code.
Your coder can position an object at a random position onscreen. She can use a random position for the x-coordinate, the y-coordinate, or both.
To set a random x-coordinate for an object in Scratch, use two commands: the set x to
number
command in the Motion category and the pick random
number
to
number
command in the Operators category. Assemble the commands as shown in Figure 5-13. The minimum value for the random command is -240, and the maximum value is 240.
To set a random y-coordinate for an object in Scratch, use two commands: the set y to
number
command in the Motion category and the pick random
number
to
number
command in the Operators category. Assemble the commands as shown in Figure 5-14. The minimum value for the random command is -180, and the maximum value is 180.
To set a random position, including both x-coordinate and y-coordinate, for an object in Scratch, use the go to random position
command in the Motion category (see Figure 5-15). Note that the go to
command tile can toggle between mouse-pointer
and random position
.
To set a random x-coordinate of an object in JavaScript, identify the object you want to position, and then use the setPosition
command along with a randomNumber
command to identify the range of x-values that you want. The minimum of the x-coordinate value is 0 and the maximum is 320.
To set a random y-coordinate of an object in JavaScript, identify the object you want to position, and then use the setPosition
command along with a randomNumber
command to identify the range of y-values that you want. The minimum of the y-coordinate value is 0 and the maximum is 450.
Here are the steps for setting a random position of an image of a mouse onscreen in the Code.org App Lab, using JavaScript. (See the JavaScript example in the previous section, “Setting and Finding Position” for details on adding an image to the screen.) This code sets both a random x-coordinate and a random y-coordinate for the image:
image("character", "mouse.png");
setPosition("character", randomNumber(0, 320),
randomNumber(0, 450), 100, 100);
Figure 5-16 shows the mouse positioned at randomly selected coordinates. The Run button is pressed three times, with the result of each press shown.
Setting the direction of an object means pointing it at any angle around a circle. Finding the direction of an object means determining the angle at which it is pointed.
The starting angle for direction is measured as 0 degrees, and there are 360 degrees of measurement as you rotate around the circle. The 360 degree direction represents a full rotation, and identifies the same direction as 0 degrees. The headings of a compass are each separated by 90 degrees. If you start at North and rotate 90 degrees clockwise, you are facing East; if you rotate another 90 degrees clockwise, you are facing South.
A typical pseudocode expression you can write to set the direction of an object is:
setHeading angle
Here, angle can be any value from 0 degrees to 360 degrees.
When your coder is working in Scratch, use the point in direction
angle
command to set the angular direction of an object. A direction of 0 degrees is North; measurement around the circle is clockwise so that 90 degrees is East, 180 degrees is South, and 270 degrees (also called -90 degrees) is West. Figure 5-17 shows a command that sets the heading to 120 degrees (which is southeast).
To find the direction of an object in Scratch, use the direction
command in the Motion category (see Figure 5-18). Your coder can use this command in her programs when she needs to write commands that require information about an object's direction.
As you code, sometimes you want to find an object’s current direction. You can do this for any sprite using either of these methods (refer to Figure 5-9):
direction
command in the Motion category to show this value onscreen.Your coder can point an object at a random angle onscreen. He can rotate an object any degree angle to create variation in the heading at which the object points.
When your coder is working in Scratch, use two commands to point an object in a random direction: the point in direction
angle
command in the Motion category and the pick random
number
to
number
command in the Operators category. The random number range is 0 to 360 degrees (see Figure 5-19).
Turning means changing the direction that an object is pointing it. You can turn an object left or right. You can also code repeated turning to create rotation, like a spinning top.
A typical pseudocode expression you can write to turn an object is:
turn angle
Here, a clockwise turn angle can be any value from 0 degrees to 360 degrees. Similarly, a counterclockwise turn can be any value from 0 to –360 degrees.
A typical pseudocode expression you can write to make an object rotate continuously is:
forever [turn angle]
This command causes the object to keep turning forever. Use a small turn angle to make the object rotate slowly. Increase the turn angle to make the object turn faster. For example, turn 10
creates a faster turn rate than turn 5
. You can also add a wait, or delay command inside the forever command to give additional control over the turn speed.
When you and your coder are working in Scratch, use a turn angle degrees
command to turn an object. There are two command tiles for the turn: a turn right
command (clockwise) and a turn left
command (counterclockwise). Use any number of degrees, including decimal values if needed, from 0 to 360 (see Figure 5-20).
See Figure 5-21 to see how you can combine the turn
command with forever
(in the Control category of commands) to make the object spin without stopping.
Moving an object means changing its position onscreen. You and your young coder can move an object whenever you want to code a car to drive or a ball to bounce.
Get up out of your seat, gather some friends, and play a little game of Traffic Light (see Figure 5-22) to set the stage for working with motion! Traffic Light is an updated version of the game Red Light, Green Light that includes a Yellow Light and turn signals. It requires players to move at different speeds, change directions, start and stop, and occasionally move backwards.
Here are the rules:
The goal is to be the first player to reach the commander — the person calling the commands.
An object moves when it changes position over time. You can program an object to move in your program using a few different commands.
Each programming language uses its own special command to move an object, and you can write different pseudocode expressions to represent the process of moving an object onscreen. The move
number
(measured in number of pixels) pseudocode command represents moving an object some distance in the direction in which the object is pointing. An example is move 5
or move 15
, with the larger number representing a larger distance moved.
Another way to make an object move is to change its x-coordinate or its y-coordinate.
changex number
changey number
Changing the x-coordinate forever creates horizontal motion. Changing the y-coordinate forever creates vertical motion.
To make an object move constantly, place a motion command inside a forever
command:
forever [move number]
forever [changex number]
forever [changey number]
To make an object move in Scratch, set the direction of the object using two commands: the point in direction
angle
command in the Motion category, and the move
number
steps
in the Operators category (see Figure 5-23). The range of point in direction
is 0 to 360 degrees. For the move
command, use any number; negative numbers move the object backwards. The larger the number, the bigger the move. Note that move
makes the sprite object move in a straight line, not spin in place.
To create horizontal motion, use change x by
number
using any number; negative numbers move the object to the left and positive numbers move the object to the right. See Figure 5-24.
To create vertical motion, use change y by
number
using any number; positive numbers move the object up and negative numbers move the object down. See Figure 5-25.
To make an object move constantly, place any motion command inside a forever
command. Figure 5-26 shows the shows the move
number
steps
inside forever
.
To make an object move in JavaScript, you code the starting position of the object and then make the position change a small quantity during a time interval.
The following code moves a mouse object left to right, across the screen in the Code.org App Lab, using JavaScript. (See the JavaScript example in the previous section, “Setting and Finding Position” for details on adding an image to the screen.) The mouse x-coordinate begins at 0. Its y-coordinate stays constant at 150.
image("character", "mouse.png");
var xpos = 0;
timedLoop(250, function () {
xpos = xpos + 1;
setPosition("character", xpos, 150, 100, 100);
});
Here's what each line of code does in this program:
image("character", "mouse.png");
xpos
) if you want to make the object move horizontally. Alternatively, create a variable for the y-position of the object (ypos
) if you want the object to move vertically. (For more information on working with variables, see Chapter 7.) Initialize the variable by setting it equal to the starting value for the object. For example, var xpos = 0;
.xpos = xpos + 1;
.setPosition
command inside the timed loop to set the object x-coordinate to xpos
.You can combine scattering, motion, and direction code to create a simple scene of objects flying and bouncing around onscreen. Adding an event such as clicking an object to make it disappear can help your coder turn the scene into a game!
Figure 5-29 shows an example of code, in Scratch, for a simple Asteroid Blaster game you can code using the commands and concepts in this chapter. All commands are on the Rocks sprite (which looks a lot like an asteroid!).
Here are some tips for writing this code:
On the Rocks sprite, assemble the code tiles in Figure 5-29. Note that the clone
command creates copies of the Rocks sprite to make it appear that many asteroids are located on the stage. Adjust the number of asteroid rocks you want to create in the repeat
code. For more information on repeats and other loops, see Chapter 10.
The Asteroid Blaster program uses a clone command to create clones of the Rocks sprite. Each clone possesses the same attributes and behaviors of the original Rocks sprite. When the program is not executing, the clones do not exist and are not visible.
The when green flag clicked
and when this sprite clicked
commands are event handlers. Event handlers react to an action by the user, such as a click, by executing some code.
The finished game looks like Figure 5-29. The user starts the game by clicking the green flag. She then tries to blast all the asteroids by clicking each one with her mouse. Try creating your own version of the game, modifying commands and the sprite object to create your own custom version!
3.15.144.170