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. :)

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. πŸ˜€

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;

About Flashmech

I have too many things in plans for my own good. But well, that's me. :) I love God, praise Him, and trust that He has the best plans in life for me.
This entry was posted in ActionScript, Flash Platform, Tutorials. Bookmark the permalink.

34 Responses to AS3 Tutorial: Moving Based On Mouse Location

  1. 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 says:

    Thanks for the encouragement Andy!

    More to come! πŸ˜€

  3. Pingback: Tutorial | Moving Based On Mouse Location using AS3 « Flash Enabled Blog

  4. Richard says:

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

  5. Chris says:

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

  6. Toby says:

    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 says:

    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. πŸ˜€

    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 says:

    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 says:

    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 says:

    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 says:

    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 says:

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

  13. flashmech says:

    You should check out the documentation. πŸ˜‰

  14. Bryon says:

    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 says:

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

    Thanks

  16. flashmech says:

    @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 says:

    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 says:

    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 says:

    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. 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 says:

    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. Buddy says:

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

    great tutorial!!

  23. peachy says:

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

    ty

    • flashmech says:

      @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. :)

  24. Corey says:

    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!

    • flashmech says:

      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. πŸ˜‰

  25. Alpha says:

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

  26. horst says:

    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

  27. Damon says:

    DUDE THANK YOU. simple, elegant, works. and it’s AS3…

  28. FZE says:

    Thanks, it’s very helpful for me.
    http://www.as3tutorial.com is very helpful for beginners.

  29. Juststeev says:

    Hi there

    A perfect example of exactly what I need but, being new to AS3, I am unsure as to where the above script goes. I’ve searched through the tutorial material and cannot find it anywhere.

    I’d like to use it in the same way as matt (as a depth thing).

    Sorry for my AS3 innocence :)

  30. Seryfe says:

    Moving the Movie Clip to the Opposite Direction

    To make The MovieClip go the opposite way you need to change line 72 istead of: var perc:Number = diff / midPt; change it to: var perc:Number = -diff / midPt; that should do it. πŸ˜€