Sunday, 13 July 2008

Follow object on mouse click

This Flash tutorial will teach you how to move an object when the mouse is clicked. So, an object will follow the mouse click. I will be using a simple circle as an example, but you can use whatever ever objects you wish. I have also used a custom cursor.

Follow object on mouse click

Step 1


Open a new Flash document.
Select the oval tool (O) and create a circle shape on the stage. You could also import an image or create whatever object on the stage.



Step 2

Select your oval and convert it into symbol by pressing F8. Give your symbol an appropriate name, check movie clip and click ok.

Give your movie clip the instance name “ball”.



Step 3

On the timeline insert a new layer called “Action” right click on 1st frame and select actions from the drop down menu.

Add the following code:

moveBall = function () {
this.dx = (this.targx-this._x)*.1;
this.dy = (this.targy-this._y)*.1;
this._x += this.dx;
this._y += this.dy;
};

setTarget = function () {
this.targx = _root._xmouse;
this.targy = _root._ymouse;

};
ball.targx = 10;
ball.targy = 10;
ball.onEnterFrame = moveBall;
ball.onMouseDown = setTarget;


**This piece of code basically moves the ball when the mouse is clicked. There are two functions: moveBall and setTarget. The moveBall function moves the ball and the setTarget moves the ball to the position of the mouse click.


Step 4

Test your movie clip Ctrl + enter and click anywhere on the stage and the object should follow your mouse. To use a custom cursor check out this tutorial.



Your object should now follow your mouse.

6 comments:

Preeth said...

i red u r tutorial ,its realy helpful thank u..


Also can i ask u 4 a favour.. I want to lern actionscript, i jst knw d play, goto such simple functions, i chkd in net 4 tutorils but i cant understand most of'em..., can u help me to get started wit it

thank u

iliketo said...

@Preeth

I don't understand your question. Can you rephase it?

lost said...

hi, i mean i really want to study action scripting, but i cant find any tutorial on net that introduces these built in functions in flash, just shows how to do this n that... thats not realy wat i want... i want to understand these things...can u help me.

iliketo said...

@Lost

What in particular do you want learn?

If you want to learn actionscript in general I recommend you going to a book shop and buying a book on actionscript. Then you will get a better understanding of how to use the functions.

Andrew said...

How do you make the ball move at the same speed to any location?

iliketo said...

@Andrew

You click on the location on the stage.

What next ?

Subscribe to Flash Tutorials

Add to Technorati Favorites

Follow my Twitter