Mouse Velocity

var velocityInfo:TextField = new TextField();
velocityInfo.x = 20;
velocityInfo.y = 20;
addChild(velocityInfo);

var prevX:Number = mouseX;
var prevY:Number = mouseY;
var velX:Number = 0;
var velY:Number = 0;

addEventListener(Event.ENTER_FRAME, onLoop);

function onLoop(evt:Event):void {
	 
	 velX = mouseX - prevX;
	 velY = mouseY - prevY;
	 
	 velocityInfo.text = velX + ", " + velY
	 
	 prevX = mouseX;
	 prevY = mouseY;
}

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.

5 comments

  1. As someone else mentioned before, you really should post SWF examples along with these ๐Ÿ˜› 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. 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. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *