Flash Tutorial: Elastic Object Follower

In this tutorial I will show you how to make one object follow another object in Flash. Then I'll show you how to make the effect more elastic. It's up to you to figure out an application for it. I use it a lot to get things to follow the mouse around.

The following scripts are written in Actionscript 3.0. However, I've also included a .fla done in Flash 8 in for anyone who wants to see it in Actionscript 2.0. If you just want the files, feel free to jump down and download them now.

We're following the leader!

So first we need to get one object to follow the other object around. Having a two year old son and a dog, I have a lot of experience with things following you. In these examples, the object follows the mouse pointer.

Getting an object to follow the mouse is fairly simple in Flash. In fact, you can just use the startDrag() function, but that sticks the object to the mouse. We'd like it to follow at a distance, so we'll need to make our own function to do that. This function will be an EnterFrame event handler.

Rather than documenting the entire script here, I'll just focus on where the real action is. The full Actionscript files are available for download at the end of the article.

private function FollowMouse(event:Event):void {
    // follow the mouse, but not too closely
    distx = follower.x - mouseX;
    disty = follower.y - mouseY;
    follower.x -= distx / 10;
    follower.y -= disty / 10;
}

Basically, all we do here is figure out how far away the follower object is from the mouse. Then we move the object a certain amount closer. Here we are moving 10% closer each frame. And here is the resulting mouse following effect.

Mouse Follower

Now add some elasticity

Now that the object is following, let's add a little personality to the effect. I know when my son is following me around, he rarely makes a straight path directly to me, nor is he always able to stop once he's caught up.

Rather than directly moving towards the mouse, we'll use momentum to insert some elasticity to the objects response. This makes it appear that the object is attached to the mouse by a rubber band. And it is surprisingly easy to do.

private function FollowMouse(event:Event):void {
    // follow the mouse in a more elastic way
    // by using momentum
    distx = follower.x - mouseX;
    disty = follower.y - mouseY;
    momentumx -= distx / 3;
    momentumy -= disty / 3;

    // dampen the momentum a little
    momentumx *= 0.75;
    momentumy *= 0.75;

    // go get that mouse!
    follower.x += momentumx;
    follower.y += momentumy;
}

You will notice that we had to dampen the momentum a little. This keeps it from bouncing indefinitely off the screen. The number you use here needs to be between 0.0 and 1.0. Anything else and you'll have flubber that shoots off the screen, never to return.

The closer this value is to 1.0, the faster your object will move and the more it will swing around. The closer it is to 0.0, the slower it will move and the less it will overshoot its target. Experiment with it a bit to get the effect you want. You can also speed or slow the object by changing the number that you divide the distance by when adjusting the momentum.

Elastic Mouse Follower

Follow another object

So now you can follow the mouse. What about when you want to follow something else? That's what makes this script so simple, just replace mouseX and mouseY with the x and y of the object you want to follow and you are set.

distx = follower.x - leader.x;
disty = follower.y - leader.y;

Download the fun

Please feel free to leave any comments or questions you may have about this tutorial. That's what the comments are all about.

This entry was posted in actionscript, Flash, Flex, Tutorials and tagged , , , , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • franco

    is there a way I can make a button follow the mouse on roll over for a short distance and then pop back to it’s original location when the mouse moves to far away.
    I can use this code you have here but I obviously have to change something in order for that effect to work.

    Thanx

  • Brandon

    keep getting the following error “1037 The package cannot be nested” also I have tried other tutorials and get this message “1087: Syntax error: extra characters found after end of program.” why does actionscript hate me? If you have answers please let me know.

    Thank you,
    Brandon

  • http://orangeSPLoTCH.com mattc

    @franco: To get the behavior you are asking for, I would store the original location of the button. Then in the enterFrame handler check how far from that coordinate the button has moved. If it is past a certain threshold reset it to the original position.

    @Brandon: I am not quite sure why Actionscript hates you. Perhaps it overheard you making snide remarks behind its back, or maybe you forgot its birthday. Whatever the case may be, it sounds like you might be having trouble setting up your packages. I dug up this thread which may help. If not, feel free to email me your code and I can see if I can help you and Actionscript have a happy healthy relationship.

  • franco

    Cool, I’ll see what I can manage with my very limited expertise…lol.

    Thanx for reply

  • mike

    I was searching for actionscripts that have this animated character that responds to mouse movements. Would be much appreciated if you share with us some basic codes 😉

  • http://orangeSPLoTCH.com mattc

    That’s a great idea for a tutorial. Are there any particular movements and responses you were interested in? A few I just though of were poking or pushing the character, or having it’s eyes/head follow the mouse.

    Let me know if you had any specifics in mind.

  • mike

    Many thanks. Nothing in specific but it will be great having its head and eyes to follow the mouse. Looking forward to the tutorial. Thanx for sharing ;-))

  • c.edward

    Actually I am writing on my behalf of my room mate, a vietnamese student, who can read but cannot express well. This is his request. He is interested in the Mouse Follower (Actionscript 3) but wonder whether you are kind enough to include the “fla” in the example. Thank you.

  • http://orangeSPLoTCH.com mattc

    Thank you for the request. The source files are available for download at the bottom of the article. There are two versions available, a Flash 8 fla file or a set of Actionscript 3.0 files with the image.

    Unfortunately, the most recent version of Flash that I own is Flash 8 so I can only provide fla’s for that release. I use the freely available Flex compiler to build my Actionscript 3 files.

  • c.edward

    This chap remarked that since you don’t have the newer version of Flash 9, you may not realize there is an error in the script. Well, I do not think he meant to be rude as he tried hard but he keeps getting the same error as what Brandon got – 1037.
    Never mind. Thanks for your attention.

  • http://orangeSPLoTCH.com mattc

    Thanks for the update. I am not sure what is causing the error, but if anyone has any ideas, please let me know. I’d like to get this resolved so future scripts won’t have the same bug.

  • http://www.worldkit.com Abel

    Fantastic!

    I learned at least three new things about 30.0 in this short tute…!

  • http://montalvo.com Doug

    FUNtastic. I learned soooo much.

  • Sacen

    Hi thanks for the as code, I’m not sure how you put it together with AS3. I need to make a MC and linkage it? I’m really new to AS3 but my project require to use as3, any help will be great

    Thanks in advance

    Sacen

  • Sacen

    Hi there

    I got it working, I converted the newmouse to MC and on the newly created MC I click on linkage then in the Class fill enter : follower and Base Class fill: Follower

    Base Class refer to the Follower.as file

    Thanks for the code again, this really helped alot

    Cheers
    Sacen

  • le_foosh

    Hi,

    I’m not sure what I’m doing wrong but I can’t get the follower to follow anything but the mouse!?

    I tried the ‘leader’ code but it wont follow anything but the mouse…?

    Help!?

    Kris

  • http://none Daniel Elffriend

    dude.. this is awesome… really—-really—really— COOK little fella…
    wonderful script….

    thanks a alot… ur awesome…

  • roger_u

    I am also trying to get an object to follow another object and its driving me crazy! I created a static movie clip labeled it ‘leader’ in the properties menu and attached it to a motion guide. Then in the script I changed mouseX and mouseY to leader.x and leader.y, no luck.

    I added frames in the actions layer to match the duration of the leader object still no luck. Tried inserting gotoAndStart(1); to the end of the script, no luck. I’ve been searching all day and I feel like I’m so close. This is killing me! You would think this would be a simple beginners AS trick but there is no documentation anywhere.

    Any reply would be greatly appreciated.

    • http://orangeSPLoTCH.com mattc

      I’ve sent you an email response so you can email me back with the details, but I’m posting a comment here as well, so hopefully help anyone else with the same problem. The best way to troubleshoot something like this is to put a trace statement in the FollowMouse function. This will let you know if the function is running every frame. If you put leader in the trace, you can see if the leader is properly linked to the MovieClip. Usually with something like this it is a problem with leader being undefined. Here is a sample trace statement to show you what I mean:
      trace ('leader: ' + leader);

  • roger_u

    By the way the mouse follow Action Script 2.0 works great running CS3 (v9.0). Thanks!