Mouse Velocity

  1. var velocityInfo:TextField = new TextField();
  2. velocityInfo.x = 20;
  3. velocityInfo.y = 20;
  4. addChild(velocityInfo);
  6. var prevX:Number = mouseX;
  7. var prevY:Number = mouseY;
  8. var velX:Number = 0;
  9. var velY:Number = 0;
  11. addEventListener(Event.ENTER_FRAME, onLoop);
  13. function onLoop(evt:Event):void {
  15.      velX = mouseX - prevX;
  16.      velY = mouseY - prevY;
  18.      velocityInfo.text = velX + ", " + velY
  20.      prevX = mouseX;
  21.      prevY = mouseY;
  22. }

Wrote this in response to a question from one of my students. The next step is to use velX and velY to push objects around the screen.

This entry was posted in motion and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. Posted November 18, 2008 at 1:33 pm | Permalink

    As someone else mentioned before, you really should post SWF examples along with these :P I know the whole point is that you can paste the code into your FLA and see what it does, but sometimes I don’t have Flash open and don’t want to read the code and just see the end result, then if I’m interested in the end result I would read the code. Granted this is an easy example, but you know what I mean. Just help the lazy people out! Keep up the great work, though.

  2. Posted November 18, 2008 at 1:56 pm | Permalink

    Yeah, I’ve been thinking about it… I may start doing that in the next couple weeks.

    I made the site because I really like to read code… and because I found myself just reading the code on peoples blogs instead of reading what they wrote about it….

  3. pra
    Posted September 17, 2009 at 1:01 am | Permalink

    this will not calculate the mouse velocity . For velocity u need formula vel = dis/time which is vector.

  4. Posted September 17, 2009 at 7:41 am | Permalink

    Thanks for the comment Pra. I always thought of it as two vector values, one for the x and one for the y - the direction is either positive or negative on either axis and the speed is in pixels per frame… How would you use the dis/time in this example?

One Trackback

  1. [...] Keys Loading, Centering & Smoothing Dynamic Vars Dictionary Mouse Velocity Toggle [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *