AS3 Tutorial: Moving Based On Mouse Location



AS3 Moving Based On Mouse Location Screenshot

Objective

  • Learn a simple way to detect location differences.
  • Make something move using that difference.

Files Required

Let’s Get Started!

In its entirety, this is a very basic tutorial. However, I’ve planned for great things through the use of this technique, so getting through the basics is necessary. :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private function __onEnterFrame ( e:Event ):void
{
	// Reposition the mc's y to the middle of stage
	mc.y = stage.stageHeight / 2;
	//
	// Find the stage's centre point
	var midPt:uint = stage.stageWidth / 2;
	//
	// Find the difference between the mouseX and midPt
	var diff:int = mouseX - midPt;
	//
	// To convert it to percentage
	var perc:Number = diff / midPt;
	//
	// Finally moving it base on the percentage
	mc.x += perc * maxSpeed;
}

The inline comments are actually pretty self-explanatory, so there’s no point in me repeating them all over again. :D

What I wish to highlight is that in line 10, diff may be either a positive or negative integer, depending on where the mouseX is. This is the key which determines which direction the square mc should be moving towards.

Final Note

If you like, you can alter this class variable, maxSpeed, to change the maximum movement speed of the square:

private var maxSpeed:uint = 10;
AddThis Social Bookmark Button


30 Comments to “AS3 Tutorial: Moving Based On Mouse Location”


rss Comments RSS
trackback Trackback
  1. Andrew D. Goodfellow on April 22nd, 2008 at 9:26 pm

    This is a great tutorial Lionel. I love that’s it’s simple, straightforward and clear. Just by playing with your demo I can see great uses for it inside more complex apps like games or 3D navigation. Thanks!

    -Andy

  2. flashmech on April 22nd, 2008 at 10:07 pm

    Thanks for the encouragement Andy!

    More to come! :D

  3. [...] Read tutorial and download support files No Comments Leave a Commenttrackback addressThere was an error with your comment, please try again. name (required)email (will not be published) (required)url [...]

  4. Richard on April 24th, 2008 at 6:40 am

    Excellent. Very concise and clear and a useful result. Thanks!

  5. Chris on May 21st, 2008 at 5:09 pm

    Great tutorial! It’s great to find some easy to understand and easy to implement actionscript! Keep it up! Cheers.

  6. Toby on July 11th, 2008 at 11:27 pm

    Hey, this is possibly the most useful tutorial ive found on the net yet and ive been searching solidly for the past two days. Im just starting out and this has been invaluable thanks so much!!!!

    One quick question in case anybody can help, how would i work out a value to see if the difference is increasing or decreasing?

  7. flashmech on July 14th, 2008 at 11:00 pm

    Hi Toby, here’s how you would work out the difference value.

    1. Create a private variable called prevDiff.
    private var prevDiff:int = 0;

    2. In the __onEnterFrame function, add the following lines AFTER this line:
    var diff:int = mouseX - midPt;
    Code to add:
    var diffDifference:int = diff - prevDiff;
    if ( diffDifference != 0 ) trace( diffDifference );
    prevDiff = diff;

    I added the if statement because too many times it’s just tracing out 0, and it’s not something that I found to be useful. :D

    After getting the difference, what’s left is to update prevDiff to be the current diff’s value.

    Hope that’s what you’re looking for! ;)

  8. matt on September 16th, 2008 at 2:42 pm

    How could I make this have bounderies. So when the object is moved to a certain point it won’t go any further.

  9. flashmech on September 16th, 2008 at 3:00 pm

    Heyo Matt,

    You’ll be glad it’s pretty simple. :)

    Comment/delete the following line.
    mc.x += perc * maxSpeed;

    And add the following in its place:
    // Store the move variant for easy access
    var move:Number = perc * maxSpeed;

    // Do a check before we actually move.
    // In this case, 100 is our left boundary, 300 is our right boundary.
    if ( mc.x + move > 100 && mc.x + move < 300 )
    {
    mc.x += move;
    }

    That's all that you need to do! If the mc is within the boundaries, it will move. If not, the code in the if block will not run. ;)

  10. matt on September 16th, 2008 at 3:18 pm

    awesome thanks, I have another question. I am using this as like a site with multiple things moving so it looks like there different depth levels and I am having trouble making buttons on my stage. any suggestions

  11. flashmech on September 16th, 2008 at 3:25 pm

    Probably you might want to let the users have a way to navigate through the depths? Meaning a zooming feature? Once they zoom in, the first few levels can probably disappear so you can still click on the buttons.

    Just remember that if you are using this approach, your boundaries have to be dynamically calculated. Base on the zoom size, you also have to fade out and change the really big ones’ visible to false.

  12. matt on September 16th, 2008 at 3:25 pm

    i keep getting this. 1046: Type was not found or was not a compile-time constant: MouseEvent.

  13. flashmech on September 16th, 2008 at 10:55 pm

    You should check out the documentation. ;)

  14. Bryon on September 24th, 2008 at 4:08 am

    Great Tut! Invaluable. I do have a couple of questions. Along the lines of Matt’s post, can you limit movement only when the mouse if over the Movie Clip? Also, how would you go about implementing this code within an FLA, not using the external AS file? Any info would be greatly appreciated. Thanks.

  15. dan on October 1st, 2008 at 3:03 am

    What is a good Loader to use for this script?
    Mine messes it up.

    Thanks

  16. flashmech on October 1st, 2008 at 10:33 am

    @Bryon
    I would certainly suggest you use it as an external class. I don’t see the reason why not to anyway. :)

    @dan
    I can’t emphasize enough the importance of exploration. Play with the code and let your creativity take over. ;)

  17. dan on October 2nd, 2008 at 2:37 am

    How can i have an external loader, that says play the external class when the loader is complete?
    I am having problems, because it is loading the script when the flash starts, I am unable to use my loader, which normally sends you to the start of the movie when complete.
    Any suggestions about loading while using an external class would be helpful.
    Thanks

  18. Johan on February 10th, 2009 at 11:18 pm

    First i want to thank you for a great tut, really neet!
    My problem is that i want to controll the speed so it ease out when it comes near any of the boundaries. How can i do that?

  19. aaron on March 13th, 2009 at 4:35 am

    for my current project i need an object to go the opposite of the mouse. i tried to put in mc.x -= move but it gets stuck at the boundaries. i don’t know if i may just be braindead from looking at code all day but ??? In my application with a slideshow it ain’t lookin so good. great tutorial!

  20. automotive floor jack on March 14th, 2009 at 8:52 pm

    I must say, that I could not agree with you in 100%, but that’s just my opinion, which could be very wrong.
    p.s. You have a very good template . Where did you find it?

  21. Marcelo on May 22nd, 2009 at 6:20 am

    Great tutorial Lionel.
    But i need to move differents mc’s in axis x in diferents speeds to create a fake 3d illusion.
    Its is possible?
    Thanks.

  22. flashmech on May 25th, 2009 at 9:14 pm

    Hi Marcelo,

    The general concept is there. For cater for your needs, you will need to experiment with it. All the best! :)

  23. Buddy on June 16th, 2009 at 9:53 pm

    flashmech
    can I put this inside a moviclip o_mc some how??

    great tutorial!!

  24. flashmech on June 16th, 2009 at 10:40 pm

    I would actually recommend using it the current way that it is, if not you might run into some scoping issues regarding the stage.

  25. peachy on July 21st, 2009 at 8:23 pm

    Hey thank you its work very fine :) . Is it possible to make something to stop the “mc” ?

    ty

  26. flashmech on July 21st, 2009 at 11:31 pm

    @peachy
    Well, you’ll need to add a conditional at the __onEnterFrame.

    If the conditional evaluates to false, then run the codes, which will make the mc move. If not, the codes will not, which essentially will stop the mc. :)

  27. Corey on November 2nd, 2009 at 7:23 am

    Hey Great tutorial, but I have one question. Is there any way you can limit the movement to only when the mouse is over the specific movieclip and not through out the whole stage? Creating like a hot spot?

    Thanks a bunch!

  28. flashmech on November 19th, 2009 at 2:10 am

    Hi Corey, that can actually be easily done with a mouse over or roll over handler for your movieclip. Then again, you might not want to use this script as a tweening engine will fit your needs better. ;)

  29. Alpha on January 12th, 2010 at 9:38 am

    This tutorial is amazing!!!! One question though, how do you make the MC move in the opposite direction of the mouse?

  30. horst on May 28th, 2010 at 3:27 pm

    great tutorial… also would love to know how to make the mc move in the opposite direction. guess it has something to do with line 10 but i dont understand how to add a negative/ positive integer.

    would be great to get some help.

    thanks

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">