Actionscript 3.0 Basics: The Moving Ball

I always thought the Moving Ball lesson my Flash lecturer gave was a very good and important lesson which provided me with the fundamentals and understanding of how things worked in Flash, particularly the onEnterFrame.

Now in AS3.0, onEnterFrame no longer exists. Events replaced everything, including this convenient function which I had come to love and hate in the past year I’ve used Flash.

This is what a general onEnterFrame looks like in AS2.0:

[code lang="actionscript"]
ball_mc.onEnterFrame = function(){
this._x += 5
}
[/code]

The above code will move the MovieClip right at a rate of 5 pixels per frame. Hence, if your movie FPS is 12, it will move 60pixels to the right per second. That’s pretty choppy. This is also why a high FPS will give you smoother animations if you didn’t know already. But I’ll leave that for a proper tutorial another time. Now, on with the Moving Ball tutorial.

The Ball I’m talking about is simply a circle shape converted as a MovieClip if you didn’t know that. We’re going to experiment a lot of stuff with this “ball” of ours in future tutorials to come, so choose a good colour to create it with.

After creating this movieclip, give it an instance name of “ball_mc”.

Here is what the AS3 code will look like to do what the same thing above:

[code lang="actionscript"]
function moveBall(e:Event):void {
ball_mc.x += 5;
}
ball_mc.addEventListener(Event.ENTER_FRAME,moveBall);
[/code]

As you can see it’s pretty similar to the code that we used for the button tutorial. The big difference and key thing to note here is the eventType. I’m using a Event.Enter_Frame here instead of a MouseEvent.MOUSE_UP. If you’re good, it means that you know that Event.Enter_Frame is what is actually the new onEnterFrame.

That about wraps up this tutorial for now. I will extend this tutorial to include the good old “delete this.onEnterFrame” function in AS3.0 soon.

3 Responses to this post.

  1. santi's Gravatar

    Posted by santi on 16.09.07 at 5:40 pm

    As far as I know, the .x doesn’t work anymore with AS3 but is replaced with DisplayObject.x

  2. jason's Gravatar

    Posted by jason on 16.09.07 at 5:40 pm

    isnt it ball_mc._x and i dont think its necessary to create a moveball function.

  3. DarkSuiyoken's Gravatar

    Posted by DarkSuiyoken on 16.09.07 at 5:40 pm

    in AS3, ._x is no longer used, and is replaced by .x.

    This moveBall function can’t earn you anything, but it lets you understand the basics, and fundamentals of animating with code in Flash. :)

Respond to this post