Spin That Dial
Flash CS4 ActionScript 3.0 Tutorial
How to Create a Random Dial Spin with Flash ActionScript
This tutorial utilizes several Flash elements such as Button Symbols, Tweens, Variables, and Object Properties. We will make a spinning dial that randomly stops at different points on the circle. The dial spins each time you press the Spin button.
Movie Symbol with instance name dialObj_mc
Button Symbol with instance name spin_btn
Open a new Flash document and add a new layer.
Name the upper layer Actions and the lower layer Content.
Click the keyframe for the Content layer.
Add a dial Movie Symbol and a Button Symbol that says Spin. Set the registration point close to the bottom for the dial Movie Symbol. For more information on creating Movie Symbols and Button Symbols, see topics, Button Symbol Basics and Movie Symbol Basics. For information on setting an object's registration point, see topic, Setting and Moving Object Registration Point.
Give the dial an instance name of dialObj_mc and the button an instance name of spin_btn.
Divide your circle into eight sections by adding a graphic to the Content layer.
Option double-click (PC - Alt double-click) the keyframe of the Actions layer to open the ActionScript panel.
Copy/Paste the following code to the ActionScript panel.
new Tween (dialObj_mc, "rotation", Back.easeIn, begin, end, 2, true);
Click the Auto Format button to format the code.
Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Press the Spin button and the dial spins. It then stops at a random point on the wheel.
Dissecting the Code
The first two lines import the Tween Class and easing package into your document. The two var lines establish new variables named begin and end. They will be used to set the rotation angle beginning and ending points.
Then next line adds a Mouse Event listener to the spin button. Each time the button is clicked, the dial rotates to a new position with the function spinDial.
The first line of the function multiplies the end value times a random number between zero and one. The Tween affects the dialObj_mc and targets the object's rotation property. The ease is set to Back and it happens in the beginning.
Once the spin is finished, the object is locked in its current position. This becomes the object's new begin value. The total rotation is a random number between zero and 2800 degrees. It occurs over 2 seconds. By setting the last parameter to true, the values are in seconds, not frames.
The begin variable is set to the end value to make the object begin with the end rotation value. The end value is then reset to 2800.