Welcome Guest | Signup | Login

Tutorials

 

Tutorials >> Mouse Dragging
DOWNLOAD SOURCE FILE FOR THIS TUTORIAL

These circles will follow your mouse around with a nice elastic effect.

First create two Movie Clip; one is for the smaller circle you can see above and the other for the rest of the circles.

Drag the smaller on to the stage and give the instance name "circle1".

Now drag the other Movie Clip 4 times, each time make it bigger and give instance names, "circle2", "circle3", etc.

Put them together, thus that the center of all circles coincide.

Every one of these instances will have code, but the only difference will be on a variable value. Paste this on all of them:
Code: Select all
//on load declare variables
onClipEvent(load)
{
//starting xspeed, how much to move on the _x.
xSpeed = 0

//starting yspeed
ySpeed = 0

//This is the "real" speed, the bigger it is
//the slower the Movie Clip will move and vise versa
Speed = 40

//if it is too high the Movie Clip will move very slowly
//and wont have elasticity, is it too low it won?t
//stop. I recommend using 1.13, but you can try different values.
Stop = 1.13
}

onClipEvent(enterFrame)
{
//move the Movie Clip
_x += xSpeed
_y += ySpeed

//get new x and y speed, using the distance between the mouse
//and the Movie Clip and the actual speed.
xSpeed +=(_root._xmouse - _x) / Speed
ySpeed +=(_root._ymouse - _y) / Speed

//this decreases the speed, so it stops
xSpeed /= Stop
//if yspeed was equal to 10, after this line it will be 10/1.13 = 8.84
ySpeed /= Stop
}

Now change the speed variable for each Movie Clip:
Code: Select all
circle1 = 40
circle2 = 45
circle3 = 50
circle4 = 55
circle5 = 60

Test the movie now. If you think the animation is too slow you need to increase the frame rate of you movie.

To do that, double click the frame rate and set it to 30.
The Movie Clips should be moving more smoothly now.

Code Explanation

Code: Select all
onClipEvent(load)
{
xSpeed = 0
ySpeed = 0

Two variable for the starting speed on the _x and _y coordinate.
Code: Select all
Speed = 40

Speed used for an easing effect, the bigger it is the slower the Movie Clip will move and vise versa.
Code: Select all
Stop = 1.13

Variable used to slow the Movie Clip down so it stops in the location of the mouse.
Code: Select all
}
onClipEvent(enterFrame)
{
_x += xSpeed
_y += ySpeed

Move the Movie Clip.
Code: Select all
xSpeed +=(_root._xmouse - _x) / Speed
ySpeed +=(_root._ymouse - _y) / Speed

Set new speeds using the distance between the current location of the Movie Clip and the position of the mouse divided by the "Speed" variable.
Code: Select all
xSpeed /= Stop
ySpeed /= Stop
}

These lines decrease both speeds until it gets in the mouse position.

That's all folks! See you in next tutorial!