Flash Tutorials

XMLStyleMellowBlueMonkey

Obejct Follow Mouse

Skill Level: Beginner
Knowledge Needed: movie clips
Number of Steps: 3
The Movie
-----------------------------------------------

------------------------------------------------
Download Flash File
Learn how to make an object follow the mouse and speed up or slow down depending on how far away the object is.

Spreadshirt
Picture 1
Step Alrighty, open up a new flash document and make 2 layers. Name them actions and ball.(top pic)
On the ball layer draw a circle with no line color (In the example above I used a circle that was 26 x 26.) Select the ball, hit F8 to convert it to a movie clip. Go into editing mode for the movie clip, select the ball and set the x and y coordinates to -13 in the properties bar.(middle pic)
This will position the ball in the center of the movie clip. Finally go back to the main timelline, select the ball Movie Clip and give it an instance name of ball_mc (bottom pic)

Step Now we are going to add a few lines of actionscript and we will be done. Pretty cool huh? Add this code on the main timeline on the actions layer
ball_mc.onEnterFrame = function() {
	var xMouse = _root._xmouse;
	var yMouse = _root._ymouse;
	if(Math.abs(xMouse - this._x) < 1) {
		this._x = xMouse;
		this._y = yMouse;
	} else {
		this._x -= (this._x-xMouse) / 6;
		this._y -= (this._y-yMouse) / 6;
	}
}
		  
We are doing a couple of things in our onEnterFrame action for ball_mc. First we find the coordinates of the mouse in the movie. Next we check to see if the ball is within one pixel of the mouse. If it is we set the ball's position to the mouse position otherwise we move the ball towards the mouse. To move it closer we are taking the distance from the ball to the mouse and dividing by 6 so that it will move slower as it gets closer to the mouse. And that is it!

Step There is many ways you can edit this code to have more functionality, so have some fun with it. If you need any help with it drop me an email. Now go play ;)

Discuss this tutorial »
Written by: Jacob Bullock
Back to Flash TutorialsTop


Copyright © 2000-2010 Spoono, LLC. All rights reserved.
Network: Reseller Web Hosting by Spoono Host | Spoonloads | Absolute Cross
Terms of Service | Privacy Policy.

kdfj