Professional Documents
Culture Documents
Chapter 6 - Creating Animated Apps
Chapter 6 - Creating Animated Apps
This chapter discusses methods for creating apps with simple animations-objects that move.
You'll learn the basics of creating two-dimensional games with App Inventor and become
comfortable with image sprites and handling events like two objects colliding.
When you see an object moving smoothly along the computer screen, what you're really seeing
is a quick succession of images with the object in a slightly different place each time. It's an
illusion not much different from "flipbooks," in which you see a moving picture by flipping
quickly through the pages (and it's also how far more sophisticated animated films are made!).
With App Inventor, you'll define animation by placing objects within a Canvas component and
moving those objects around the Canvas over time. In this chapter, you'll learn how the Canvas
coordinate system works, how the Clock.Timer event can be used to trigger movement, how to
control the speed of objects, and how to respond to events such as two objects colliding.
OBJECTIVES:
Explain how the canvas coordinate.
Analyze how the canvas system works.
Understand how to control the speed of objects.
Learn how you can use the Clock. Timer event to trigger movement; and
Discuss and describe how to respond to events such as two objects crashing into each
other
FUNDAMENTALS OF MOBILE TECHNOLOGY
You can do the same for the Height, but generally you'll set it to some number (e.g., 300 pixels)
to leave room for other components above and below the Canvas.
The Canvas Coordinate System
A drawing on a canvas is really a table of pixels, where a pixel is the tiniest possible dot of color
that can appear on the phone (or other device). Each pixel has a location (or table cell) on the
canvas, which is defined by an x–y coordinate system, as illustrated in Figure 2. In this
coordinate system, x defines a location on the horizontal plane (left to right), and y defines a
location on the vertical plane (up and down).
FUNDAMENTALS OF MOBILE TECHNOLOGY
Each cell of the canvas holds a pixel defining the color that should appear there.
The Canvas component provides the Canvas.DrawLine and Canvas.DrawCircle blocks for
painting pixels on it. You first set the Canvas.PaintColor property to the color you want and
then call one of the Draw blocks to draw in that color. With DrawCircle, you can paint circles
of any radius, but if you set the radius to 1, as shown in Figure 3, you'll paint an individual
pixel.
FUNDAMENTALS OF MOBILE TECHNOLOGY
Figure 3. DrawCircle with radius 1 paints an individual pixel with each touch
App Inventor provides a palette of 14 basic colors that you can use to paint pixels (or component
backgrounds). You can access a wider range of colors by using the color numbering scheme
explained in the App Inventor documentation at
***http://appinventor.googlelabs.com/learn/reference/blocks/colors.html.
The second way to modify the appearance of a canvas is to
place Ball and ImageSprite components on it. A sprite is a graphical object placed within a
larger scene-in this case, a canvas. Both the Ball and ImageSprite components are sprites; they
are different only in appearance. A Ball is a circle whose appearance can only be modified by
changing its color or radius, whereas an ImageSprite can take on any appearance and Balls can
only be added within a Canvas; you can't drag them into the user interface outside of one.
After adding a Clock and setting a TimerInterval in the Designer, you can drag out
a Clock.Timer event in the Blocks Editor. You can put any blocks you like in this event, and
they'll be performed every time interval.
Creating Movement
To show a sprite moving over time, you'll use the MoveTo function found in both
the ImageSprite and Ball components. For example, to move a ball horizontally across the
screen, you'd use the blocks in Figure 4.
If you wanted to move the ball diagonally, you'd add an offset to both the x and y coordinates, as
shown in Figure 5.
Figure 5. Offsetting both the x and y coordinates to move the ball diagonally
Speed
How fast is the ball moving in the preceding example? The speed depends on both
the Clock's TimerInterval property and the parameters you specify in the MoveTo function. If
the interval is set to 1,000 milliseconds, that means an event will be triggered every second. For
the horizontal example shown in Figure 4, the ball will move 20 pixels per second.
But a TimerInterval of 1,000 milliseconds doesn't provide very smooth animation; the ball will
only move every second, and this will appear jerky. To get smoother movement, you need a
smaller interval. If the TimerInterval was set instead to 100 milliseconds, the ball would move
20 pixels every tenth of a second, or 200 pixels per second-a rate that will appear much smoother
to anyone using your app. There's another way to change the speed instead of changing the timer
interval-can you think of what that is? (Hint: Speed is a function of how often you move the ball
and how far you move it each time.) You could also alter speed by keeping a timer interval of
1,000 milliseconds and instead changing the MoveTo operation so the ball only moves 2 pixels
every time interval-2 pixels/100ms is still 20 pixels/second.
FUNDAMENTALS OF MOBILE TECHNOLOGY
EdgeReached
Consider again the animation in which the object is moving diagonally from the top left to the
bottom right of the canvas. As we programmed it, the object would move diagonally and then
stop when it reached the right or bottom edge of the canvas (the system won't move an object
past the canvas boundaries).
If you instead wanted the object to reappear at the top-left corner after it reaches the bottom
right, you could define a response to the Ball.EdgeReached event shown in Figure 6.
Figure 6. Making the ball reappear at the top-left corner when it reaches an edge
EdgeReached (an event that is applicable only for sprites and balls) is triggered when
the Ball hits any edge of the canvas. This event handler, combined with the diagonal movement
specified with the previously described timer event, will cause the ball to move diagonally from
top left to bottom right, pop back up to the top left when it reaches the edge, and then do it all
over again, forever (or until you tell it otherwise).
Note that there is an argument, edge1, with the EdgeReached event. The argument specifies
which edge the ball reached, using the following directional numbering scheme:
North = 1
Northeast = 2
East = 3
Southeast = 4
South = –1
Southwest = –2
West = –3
Northwest = –4
FUNDAMENTALS OF MOBILE TECHNOLOGY
Figure 7. Making the ball change color and play an explosion sound when it hits another object
NoLongerCollidingWith provides the opposite event of CollidedWith. It is triggered only
when two objects have come together and then separated. So, for your game, you might include
blocks as shown in Figure 8.
Figure 8. Changing the color back and stopping the explosion noise when the objects separate
Note that both CollidedWith and NoLongerCollidingWith have an argument, other.
other specifies the particular object you collided with (or separated from). This allows you to
perform operations only when the object (e.g., Ball1) interacts with a particular other object, as
shown in Figure 9.
FUNDAMENTALS OF MOBILE TECHNOLOGY
Figure 10. Stopping the timer the first time the button is clicked
After the Clock1.TimerEnabled property is set to false, the Clock1.Timer event will no longer
trigger, and the ball will stop moving.
Of course, stopping the movement on the first click isn't too interesting. Instead, you could
"toggle" the movement of the ball by adding an ifelse in the event handler that either enables or
disables the timer, as shown in Figure 11.
This event handler stops the timer on first click, and resets the button so that it says "Start"
instead of "Stop." The second time the user clicks the button, the TimerEnabled is false, so the
"else" part is executed. In this case, the timer is enabled, which gets the object moving again,
and the button text is switched back to "Stop." For more information about ifelse blocks, see
Chapter 18, and for examples of interactive animations that use the orientation sensor, see
Chapters 5 and 23.
Figure 11. Adding an ifelse so that clicking the button starts and stops the movement of the ball
FUNDAMENTALS OF MOBILE TECHNOLOGY
Figure 13. Changing the ball's direction when it reaches either edge
LABORATORY ACTIVITY
You'll design the game so that the mole moves once every half-second. If it is touched,
the score increases by one, and the phone vibrates. Pressing restart resets the score to
zero.
This tutorial introduces:
image sprites
timers and the Clock component
procedures
picking random numbers between 0 and 1
text blocks
typeblocking
FUNDAMENTALS OF MOBILE TECHNOLOGY
You need to arrange for the mole to jump periodically, and you'll do this with the aid of
a Clock component. The Clock component provides various operations dealing with
time, like telling you what the date is. Here, you'll use the component as a timer that
fires at regular internals. The firing interval is determined by the Clock
's TimerInterval property. Drag out a Clock component; it will go into the non-visible
components area. Name it "MoleTimer". Set its TimeInterval to 500 milliseconds to
make the mole move every half second. Make sure that TimerEnabled is checked.
Adding an Image Sprite
To add the moving mole we'll use a sprite.
Sprites are images that can move on the screen within a Canvas. Each sprite has
a Speed and a Heading, and also an Interval that determines how often the sprite
moves at its designated speed. Sprites can also detect when they are touched.
In MoleMash, the mole has a speed zero, so it won't move by itself. Instead, you'll be
setting the mole's position each time the timer fires. Drag an ImageSprite component
FUNDAMENTALS OF MOBILE TECHNOLOGY
onto the Viewer. You'll find this component in the Drawing and Animation category of
the Palette. Place it within MyCanvas area. Set these properties for the Mole sprite:
Picture: Use mole.png, which you downloaded to your computer at the beginning of this
tutorial.
Enabled: checked
Interval: 500 (The interval doesn't matter here, because the mole's speed is zero: it's
not moving by itself.)
Heading: 0 The heading doesn't matter here either, because the speed is 0.
Speed: 0.0
Visible: checked
Width: Automatic
Height: Automatic
You should see the x and y properties already filled in. They were determined by where
you placed the mole when you dragged it onto MyCanvas. Go ahead and drag the mole
some more. You should see x and y change. You should also see the mole on your
connected phone, and the mole moving around on the phone as you drag it around in
the Designer. You've now specified all the components. The Designer should look like
this. Notice how Mole is indented under MyCanvas in the component structure list,
indicating that the sprite is a sub-component of the canvas.
Component Behavior and Event Handlers
Now you'll specify the component behavior. This introduces some new App Inventor
ideas. The first is the idea of a procedure. For an overview and explanation of
procedures, check out the Procedures page.
A procedure is a sequence of statements that you can refer to all at once as single
command. If you have a sequence that you need to use more than once in a program,
you can define that as a procedure, and then you don't have to repeat the sequence
each time you use it. Procedures in App Inventor can take arguments and return
values. This tutorial covers only the simplest case: procedures that take no arguments
and return no values.
Define Procedures
Define two procedures:
FUNDAMENTALS OF MOBILE TECHNOLOGY
MoveMole does not take any arguments so you don't have to use the mutator function of
the procedure block. Observe how the blocks connect together: the first statement uses
the Mole.X set block to set mole's horizontal position. The value plugged into the block's
socket is the result of multiplying:
1. The result of the call random fraction block, which a value between 0 and 1
2. The result of subtracting the mole's width from the canvas width
The vertical position is handled similarly.
With MoveMole done, the next step is to define a variable called score to hold the score
(number of hits) and give it initial value 0. Also define a procedure UpdateScore that
shows the score in ScoreLabel. The actual contents to be shown in ScoreLabel will be
the text "Score: " joined to the value of score.
To create the "Score: " part of the label, drag out a text block from the Text drawer.
Change the block to read "Score: " rather than " ".
Use a join block to attach this to a block that gives the value of the score variable. You
can find the join block in the Text drawer.
Here's how score and UpdateScore should look:
FUNDAMENTALS OF MOBILE TECHNOLOGY
Add a Timer
The next step is to make the mole keep moving. Here's where you'll use MoleTimer.
Clock components have an event handler called when ... Timer that triggers repeatedly
at a rate determined by the TimerInterval.
Set up MoleTimer to call MoveMole each time the timer fires, by building the event
handler like this:
Notice how the mole starts jumping around on the phone as soon as you define the event handler. This is an
example of how things in App Inventor start happening instantaneously, as soon as you define them.
Add a Mole Touch Handler
The program should increment the score each time the mole is touched. Sprites, like
canvases, respond to touch events. So create a touch event handler for Mole that:
1. Increments the score.
2. Calls UpdateScore to show the new score.
3. Makes the phone vibrate for 1/10 second (100 milliseconds).
4. Calls MoveMole so that the mole moves right away, rather than waiting for the timer.
Here's what this looks like in blocks. Go ahead and assemble the when
Mole.Touched blocks as shown.
Variations
Once you get the game working, you might want to explore some variations. For
example:
Make the game vary the speed of the mole in response to how well the player is doing.
To vary how quickly the mole moves, you'll need to change
the MoleTimer's Interval property.
Keep track of when the player hits the mole and when the player misses the mole, and
show a score with both hits and misses. To do this, you'll need do define touched
handlers both for Mole, same as now, and for MyCanvas. One subtle issue, if the player
touches the mole, does that also count as a touch for MyCanvas? The answer is yes.
Both touch events will register.
Review
Here are some of the ideas covered in this project:
Sprites are touch-sensitive shapes that you can program to move around on a Canvas.
The Clock component can be used as a timer to make events that happen at regular
intervals.
Procedures are defined using to procedure blocks.
For each procedure you define, App Inventor automatically creates an associated call
block and places it in the Procedures drawer.
Making a random-fraction block produces a number between 0 and 1.
Text blocks specify literal text, similar to the way that number blocks specify literal
numbers.
Typeblocking is a way to create blocks quickly, by typing a block's name.
FUNDAMENTALS OF MOBILE TECHNOLOGY
QUIZ. Answer each of the following question below by writing the correct answer on the space
provided before the number.
1. You can drag a Canvas component into your app from the Basic palette.
a) Yes
b) No
c) Maybe
2. If you want the Canvas to span the width of the device screen. To do this,
choose Fill parent when specifying the Width.
a) Yes
b) No
c) Maybe
3. A drawing on a canvas is really a table of graphics
a) Yes
b) No
c) Maybe
4. A pixel is the tiniest possibledot of color that can appear on the phone (or other
device).
a) Yes
b) No
c) Maybe
5. Each pixel has a location(or table cell) on the canvas, which is defined by an x–
y coordinate system.
a) Yes
b) No
c) Maybe
6. the top-left cell in a Canvas starts with 0 for both coordinates, so this position is
represented as (x=0,y=0).
a) Yes
b) No
c) Maybe
7. As you move right, the x coordinate gets larger; as you move down, the y
coordinate gets smaller.
a) Yes
b) No
c) Maybe
8. You can change the appearance of the canvas in two ways: (1) by painting on
it, or(2) by placing and detecting images within it.
a) Yes
b) No
c) Maybe
9. Each cell of the canvas holds a pixel defining the color that should appear
there.
a) Yes
b) No
c) Maybe
10. The Canvas component provides
the Canvas.DrawLine and Canvas.DrawCircle blocks for painting pixels on it.
a) Yes
b) No
c) Maybe
11. To show a sprite moving over time, you'll use the MoveTo function found in
both the ImageSprite and Ball components.
a) Yes
b) No
c) Maybe
FUNDAMENTALS OF MOBILE TECHNOLOGY
LABORATORY ACTIVITY
FUNDAMENTALS OF MOBILE TECHNOLOGY
Content
The student included The student included 2 The student included 4 The student included all
none or 1 of the or 3 of the required or 5 of the required 6 of the required
required components:<BR> components:<BR> components:<BR>
components:<BR> button, images, canvas button, images, canvas button, images, canvas
button, images, canvas and invisible and invisible and invisible
and invisible components (sound, components (sound, components (sounds,
components (sound, arrangements, arrangements, arrangements, sensors)
arrangements, sensors) sensors)
sensors)
Functionality
Less than 60% of the 60-70% of the app is 80-90% of the app is 100% of the app is
app is working. working. working. working on emulator or
phone.
SUMMARY
FUNDAMENTALS OF MOBILE TECHNOLOGY
Animation is an object being moved or otherwise transformed over time, and App Inventor
provides some high-level components and functionality to facilitate it. By programming
the Clock component's Timer event, you can specify any type of animation, including object
movement-the fundamental activity in almost any type of game.
The Canvas component allows you to define a subarea of the device's screen in which objects
can move around and interact. You can put only two types of
components, ImageSprites and Balls, within a Canvas. These components provide high-level
functionality for handling events such as collisions and reaching a Canvas edge. They also have
properties-Heading, Speed and Interval-that provide an alternative method of movement.
REFERENCES:
App Inventor 2, Creating you won Android Apps – David Wolber, Hal Abelson, Ellen
Spertus, and Liz Looney 2015
https://www.youtube.com/watch?v=dVRpJK-LsL4
https://appinventor.mit.edu/explore/ai2/molemash