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


17 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

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="">