27.3.15

Point at Pointer 2

Now that you're on the main stage with your new symbol instance, create a new layer. This layer will hold our Actionscript 3.0 code, from the Actions panel. Flash doesn't allow Actionscript to be on a layer that has display objects in it, so we have to create a new black layer. You can name the layer if you wish. In this new layer, on frame one, select f9 to go into the actions panel. Here is the code that you must enter:

addEventListener(Event.ENTER_FRAME, rotateTriangle, false, 0, true);

function rotateTriangle(e:Event) {
    var angle:Number = Math.atan2(mouseY - triangle.y, mouseX - triangle.x);
    triangle.rotation = angle * (180 / Math.PI);
}

Okay, this is the code that runs the mouse follow program. In order for this program to work, the program has to know what to do and when. In this case, we're answering the second question first, with our Event Listener. As the name suggest, an Event Listener waits for something to happen and then does something. There are many things that it can listen for. In our case, we need to wait for the mouse to move, because that's what we're following. But how do we do this? Logically, you would say that we need to write a function that says that whenever the mouse moves, the triangle should change direction.

If you look at the part highlighted in red, our Event Listener is actually going to do something every time that an event called "Enter_Frame" happens. What is ENTER_FRAME? It is the frame rate. Basically, every time a frame passes in Flash, an ENTER_FRAME event is sent out. So if your Flash movie is set at the default 24 frames per second, ENTER_FRAME happens 24 times every second.

I know what you're thinking: "But we don't need to track the rotation of the triangle every frame of the animation. It only needs to be moved when the mouse moves." While it is true that we would save some memory if the computer only had to keep track of the triangle's rotation when the mouse actually moved, it would take more work than it was worth to implement such functionality. And besides, if there is a constant stream of events, happening every frame, we won't have to worry about input lag.

Input lag is the amount of time that it takes for a machine to respond to your input. It might be one millisecond, but it's still detectable. If we were to rotate the triangle only when the mouse moved, we would have to wait for the computer to see the mouse move, load up the program and execute the function. By having our function run with the frame rate, however, we keep the computer on its toes so that it doesn't get caught napping. If there is any slowdown as a result of over-use, it will be spread out across 24 frames, instead of being concentrated at the initial frame, when the computer first detected the movement of the mouse.

 


No comments:

Post a Comment