Animation - Hello App Inventor!: Android programming for kids and the rest of us (2015)

Hello App Inventor!: Android programming for kids and the rest of us (2015)

Chapter 8. Animation

As we’ve explained in previous chapters, Android devices can do many things. But when learning to program, one of the first things young people usually want to do is create a game, and this often involves animation. Have you ever used or made a flip book—you know, the ones with a stick person walking along the bottom of the page or slam-dunking a basketball? When you see something moving smoothly across a screen, whether it’s a cartoon or a game, what you’re really seeing is a sequence of quickly changing pictures, like in a flip book. Imagine animating a walking zombie. Its position needs to change, which can be achieved by adjusting the zombie’s speed, the direction it’s heading in, and how often it moves (heading and interval properties) in the App Inventor Designer or by letting the user interact with the zombie by clicking buttons, dragging the sprite, tipping the phone, and so on. But if you don’t change the position of the zombie’s legs, it appears to be frozen or floating. To do this in App Inventor, you use a clock timer and lists of images that change each time the zombie moves, giving the appearance of walking rather than floating.

In chapter 3, we briefly explained the coordinate system; in chapter 4, you had a go at designing apps with user interaction; and in chapter 6, you saw the clock in action. In this chapter, we’ll show you how to create short animations and exciting games using these things and more.

Note

Full games can be long, involved programs, so while you’re at the learning stage we’re providing short projects rather than full games.

Animation type 1: moving sprites using properties

Without using the clock timer or any intervention from the user, you can create the illusion of movement by using the properties Heading, Speed, and Interval. These properties can be set in the App Inventor Designer before you even reach the Blocks Editor. The following mini app demonstrates something that could be used as part of a bigger game. Give it a try: it’s quick to put together and good fun. (Ballybally is what my [Paula’s] nephew used to call pool when he was 4 years old.)

Ballybally app

PURPOSE OF THIS APP

This mini app demonstrates the use of properties in the Designer to make a ball appear to bounce from one corner to another, changing the canvas color as it does so.

APP RATING

ASSETS YOU’LL NEED

None!

1. The properties explained

Because most of the work is done in the Designer we’ll give an explanation of each of the properties. We encourage you to tinker with the properties once you’ve completed the app and have the emulator open to see what difference your changes make to the app’s behavior. Sprites and balls default to Heading 0 (heading east), Interval 100 (moving every 1/10 of a second), and—the important part—Speed 0.0. We know Heading 0 being east is a bit peculiar, but as a default it makes sense to go from left to right. In order for your sprite to move, you need to give it some speed (explained further in a moment).

Learning Point: Reminder about setting properties!

You should think of properties as a jumping-off point for components. You might start with a ball that has a Radius property of 10 and change the property in your coding. But every time you restart (or initialize) the app, all properties go back to those set in the Designer.

Heading

The Heading property in App Inventor can be set to anything between 0 degrees and 360 degrees.

The Heading numbering system is a little peculiar in App Inventor, with 0 being to the right and 180 being to the left. But as long as you use this diagram as a guide, you’ll be fine. The Heading property means the direction of travel the ball or sprite is “heading” in when the app initializes. For this app, we advise you to set the Heading property of the ball to 315 degrees. This means if you’ve positioned the ball in the top-left corner of the screen, it will head southeast, roughly toward the bottom-right corner of the screen. Later, in the Blocks Editor, you’ll change the heading to 135, which is the opposite direction of 315 degrees and makes the ball head northwest (in this case, back to the top-left corner).

Interval

The Interval property lets the app know how frequently (in milliseconds) you want the ball or sprite to move. The smaller the interval, the smoother the animation appears. For Ballybally, you set Interval to 5 milliseconds, which means the ball moves once every 5/1000 of a second. The default interval for a ball is 100 milliseconds, which is 1/10 of a second.

Speed

The speed is measured in pixels: that is, how many pixels do you want the ball to travel per interval? The default speed is 0.0 (stationary); in this app you set it to 5 pixels per 5/1000 of a second, which gives a fast, smooth action.

2. Coding the blocks: identifying that the edge has been reached, an- nd testing which way the ball is heading

When sprites collide with the edge of the screen or each other, they trigger an event. In this case, you’re using the event Ball1.EdgeReached. In response to these blocks, when the edge of the screen is reached, the app asks, “Is the ball heading in the direction 315?”

3. Responding to the direction of travel

The control block is needed to determine which way the ball is heading when it hits the edge. If it’s heading 315, you make it head to 135; and if it’s heading 135, you make it head to 315, so it boings back and forth!

4. Changing the color of the canvas when the edge is reached

Once you’ve set up the coding for an if ... else ... then ... do block, you can make a number of things happen when the conditions are satisfied. Just for fun, in this app you make the canvas background color change each time the ball reaches the edge of the screen.

Animation type 2: Creating movement with a clock timer and user interaction

The previous app showed how you can create the illusion of movement by giving the sprite properties of speed and a heading direction, and then making it appear to bounce off the screen edges. In this type of animation, you use an internal clock to remind the app to do something every so often, thereby making it appear to be animated. You also let the user tap the screen to enable movement.

Cheeky Hamster app

PURPOSE OF THIS APP

In this mini game, a bored hamster empties its pouch back into its randomly moving bowl by shooting seeds out of its mouth. When tapped by the user, the hamster shoots the seeds toward the food bowl and only gets to keep them if the seeds hit the moving target.

APP RATING

ASSETS YOU’LL NEED

Image sprites: Cheekyhamster.png, Bowl.png, Hamstericon.png.

In this app, you use the clock timer to provide animation, and you also get the user to interact with the sprite via buttons to move the sprite around on the screen. In the previous chapter, you were particular about the ball’s Interval and Speed properties. It’s important to note that when you’re using a clock timer with a sprite or ball, the timer’s Interval number effectively overrides the sprite’s or ball’s Interval property—but it’s still important to set the correct initial heading for the sprite or ball in the Designer.

Tip

Don’t forget that although there are up to 12 properties to set for each component, you should leave them at the default values unless we specify that you should change them.

The coding for Cheeky Hamster isn’t too difficult and gives some great results. The three things that happen in the app—shooting, random sprite movement, and moving sprites with buttons—can be used in lots of other games. So once you’ve used them, you’ll know how to do these things for your own game design.

1. Coding the blocks: setting the BowlClock timer

BowlClock.Timer does the job of making the bowl move to random locations across the top of the screen every two seconds. Only the X coordinate of the bowl changes, because the bowl stays in the same vertical position throughout. Drag out the BowlClock.Timer block, and put in the blocks as shown. You want the bowl to appear at a random position, so choose random integer and Number blocks between 0 and 300.

2. Moving the hamster

The coding for the left and right buttons is the same, except one uses the subtraction Math block and the other uses addition. After accessing the LeftButton.Click block, insert blocks to move the hamster 20 pixels for each click. We chose 20 pixels because the moves are big enough for the user to see but small enough for the user to be accurate with placing the hamster.

3. Shooting seeds

This step is a little more complicated, because you need to position the seed so it appears to be coming out of the hamster’s mouth. If you reproduce this app and use your own image, you’ll have to do this by trial and error, relative to the position of the hamster. Some people post screencast tutorials on the web, and it’s hilarious to watch them trying to position things in the right spot. One guy I watched took 15 minutes of his airtime positioning a sprite and kept forgetting partway through whether the X coordinate was too big or too small. Anyway, we (in the privacy of an office, un-videoed) have discovered that if you position the seed at HamsterSpriteX + 58 and HamsterSpriteY + 22, it looks about right. You can see in the screenshots that you adjust these settings in the call Seed.MoveTo event handler.

It may seem unusual to be setting the timer to Enabled and the seed to Visible. You do so because once the user shoots the seed, it has to disappear off the screen in order to start again from the hamster: at that point, you’ll disable the timer and make the seed not visible. In summary, when the user touches the hamster, these things happen:

1. App Inventor detects the touch.

2. The seed appears, enabled and visible, at the hamster’s mouth.

3. The seed immediately (moved by its own Interval, Heading, and Speed properties) moves up the screen.

4. Making the seed disappear at the edge of the screen

If you don’t tell the app what to do with the seed once it has been shot, the seed will sit at the top of the screen going nowhere. The following bit of code instructs it to stop moving and disappear when it reaches the edge.

5. Scoring when the seed hits the bowl

In order for the player to score, a seed needs to hit the bowl. App Inventor has provided a great event handler for this called CollidedWith, which you’ll use in lots of games.

The event handler Seed.CollidedWith automatically produces a variable named other. This means it’s reporting when the seed collides with any component (which could include the hamster). In this case, you want a score to occur when the seed collides with BowlSprite, so you use an if ... then ... do test to check that in this case the score increases only if the seed collides with the component BowlSprite.

6. Resetting the score

The score automatically resets each time you start the app. But if you want to reset it while playing, it’s simple to reset the Scorelabelcount.Text back to 0:

Taking it further

1. The Cheeky Hamster app could involve a scoring and levelling system by making the bowl smaller or faster-moving.

2. You may have noticed that if you press the hamster again before the seed reaches the top of the screen, another seed appears and the original one disappears. To enable the user to shoot lots of seeds in quick succession, you could try having five seed sprites that fire one after the other. Then, tapping five times will release five separate seeds; by the time the fifth one reaches the top, the first one will be ready to go again.

Animation type 3: creating movement using lists and a clock timer

To create the genuine illusion (is that an oxymoron?!) of animation, you need to combine a change in position with a change of image. To make professional-looking animations, you need many different frames. In this chapter, we’ll teach you how to pick images from lists and move them around the screen. Then, if you want to go further, you’ll have the skills to do so.

The app you’ll work on shortly uses 10 images of a spider in motion. Remember that at the beginning of the chapter, we talked about animation actually being a quick succession of pictures changing. Well, first you have to ensure that you have the right pictures to begin with. The crawling motion of a spider is produced by its odd-numbered legs moving together, followed by its even-numbered legs moving.

After about 50 rubbish attempts at cutting up one spider picture and reattaching the legs to look like a crawling spider, we threw in the towel. Our animated spider looked more like one that had been chewed by a cat! Bleuggh. So we did what all sensible people do: we borrowed from somebody who is a lot better at this side of things. We took an existing animated GIF of a crawling spider and exploded the file to reveal the 10 frames that produce the illusion of crawling. These images are from http://heathersanimations.com/, which is a great website that provides fantastic free images.

Creepy Spider app

PURPOSE OF THIS APP

This mini app demonstrates the use of the clock and lists to produce an animated creeping spider. The spider continually crawls across some rotting leaves. When the user touches the spider, it makes a convincing chomping sound, vibrates, and stops moving. When the user takes their finger off the spider, it sets off again.

APP RATING

ASSETS YOU’LL NEED

Image sprite: Spider1frame.gif (10 images, 1–10). Canvas image: leavesbackground.jpg. Sound: spiderbitesound.wav. Image: creepyspider.png.

1. Coding the blocks: making the spider appear to crawl

Despite looking simple, this app involves quite a lot of coding. The first thing you need to do is download the 10 images and upload them into your App Inventor Media area in the Designer. You only use Spider1Frame.gif for SpiderImageSprite, but you need the rest available for later.

Learning Point: Exploding GIFs

An animated Graphics Interchange Format (GIF) file is a graphic image that’s usually shown on a web page and that appears to move. To create this illusion of movement, the GIF contains any number of images that loop endlessly in succession. If you want to look at the separate images of the animated GIF, you have to “explode” it, like a flipbook! A useful website to achieve this quickly is http://gif-explode.com/.

In App Inventor, you make a list by defining two essential elements: a variable, and an index that enables you to refer to the items in the list by number and progress through them in order. The following diagram shows the List block you need to assemble.

To make App Inventor count through a list, you need an index to go with it. All the index does is say to App Inventor, “The first item in the list is called 1, the second is called 2, and so on.” This means you can easily identify where the end of the list is, using the length of the list.

The blocks that follow enable the spider to change images every tenth of a second. How frequently you change the image depends on the effect you’re trying to produce. The changes in image are handled by Clock1.Timer.

You may remember that in chapter 3 we discussed giving the program a voice to help understand what is going on. Well, the clock definitely has a nagging, persistent voice. In this capacity, the timer is more like a reminder bell going off every tenth of a second, saying “Don’t forget to show the next image!” Of course, the program doesn’t understand “next image”; but because you’ve given the list an index, it does understand that every time the timer reminder goes off, the index number has 1 added to it. The app effectively counts through the list, displaying first Spider1frame, then Spider2frame, and so on.

We experimented for a while before settling on changing the image every tenth of a second (100 milliseconds) to give a smooth and scarily quick look to the crawl!

Next you need to make the link between the index and the image change by inserting a Clock1.Timer event hander. It counts through the index and changes the spider picture each time the index calls the next picture in the list.

The last thing you do in this section is return the count to the beginning of the list so Spider1frame is shown again, enabling you to loop through the crawl. You tell the program that when the index has reached more than 9 (that is, 10), it’s at the end of the list of images, so it should go back to the beginning and start again.

Don’t be disheartened by how much goes into changing the costume of the spider. You may be thinking that it’s much easier in a program like Scratch. But once you understand this listing sequence, you can use almost identical coding any time you want to run through a list, be it of images or quiz questions, for example.

Learning Point: Scratch

Scratch is a super-fun programming language that is looked after by the same people as App Inventor (Massachusetts Institute of Technology [MIT]). It is a bit like the App Inventor Designer and Blocks Editor rolled into one, and it lets you put animations and games together quickly on a computer. Have a look: http://scratch.mit.edu/.

2. Making the spider move repeatedly

The settings you’ve given the spider in the App Inventor Designer will make it head diagonally down the screen without you doing anything else. Just as a reminder, the settings for SpiderImageSprite are as follows:

Setting

In English!

Heading: 225

Moves toward the bottom-left corner of the screen

Interval: 100

Moves every 1/10 of a second

Speed: 5

Moves 5 pixels each time

X: 190 Y: 10

Starts in the top-right corner of the screen

If you left these settings alone, the spider would head down the screen and stay there. But you want her (him or her—how can you tell?) to hit the edge of the screen and then appear again in the top-right corner. In order to do this, you need to tell the spider, “If you reach the edge of the screen, get yourself back up to X = 190 and Y = 10.” Then the spider is free to do it all again.

3. Making the spider bite and stay still

Now you can use a new set of events called TouchDown and TouchUp. When the user touches the spider and holds their finger still, the spider responds by making a biting noise, vibrating, and staying still. As soon as the user takes their finger off the spider, it carries on crawling. You want the spider to appear to bite at the moment the user puts their finger on the spider image. The blocks to achieve this are shown next.

4. Making the spider start moving again

You know already that to stop the spider, you set SpiderImageSprite.Enabled to false. What do you think you need to do to make it walk again? That’s right: set enabled to true. You also want to restore the spider’s speed to 5 for the speedy, scary crawl. But in this event, you don’t want the spider to bite, so you don’t mention the sound or vibration.

Taking it further

1. In Creepy Spider, you could provide some variety by changing the background every time the spider is touched. This would involve adding an extra action in the TouchDown event handler to change the background image of the canvas.

2. You could introduce levels of difficulty by making the background more and more difficult to find the spider on, or by making the spider smaller. The user could score depending on how quickly they touch the spider. Taking inspiration from the “Where’s Waldo?” illustrations, you could make the boss level lots of pictures of stationary spiders among which to find the moving one.

3. Rotate the spider, and have it head the other way across the screen rather than reappear at the top.

What did you learn?

In this chapter, you learned the following:

· How to create movement without a clock timer or any user interaction

· How to create random movement with a clock timer

· How to create movement with a clock timer and lists

· How to apply your list and index knowledge to animation

· How to explode GIFs so you can use the images in your own animations

· How to use the EdgeReached event handler

· How to use built-in Logic blocks

Test your knowledge

1

What are the three ways of producing animation in an app?

2

What are the default settings for Heading, Speed, and Interval for a sprite or ball?

3

What is an animated GIF, and what do you have to do to one to use it in your app?

4

If you want a ball to head straight down the screen, what Heading value do you assign it?

5

What does a speed of 5 mean?

6

What does an interval of 100 mean?

7

Which event-handling block would you use to make a sprite change in some way when it reached the edge of the screen?

8

In which block drawer do you always find the block that should be used when you want to refer to a sprite?

9

How do you switch off a Clock.Timer?

10

When you’ve defined a list, what else do you always need to define if you want to count through the list?

11

Is Carl scared of spiders?