Tuesday 19 June 2007

Anchoring Random Placement


I want to randomly place a symbol somewhere on stage, but I want it to stay anchored around a specific point so it won't wander off the stage. What can I do?

This was previously covered in the Vibrating Objects tutorial. Here are the steps:

1) Create a graphic symbol of the object you want to randomly place
2) Create a movieclip, place the graphic symbol inside. Give the graphic an instance name: we will call ours ball. Extend the movieclip to 2 frames long.
3) In Frame 1 of the movieclip, add actionscript:

/:x_displacement = random(2*/:boundary)-/:boundary;
/:y_displacement = random(2*/:boundary)-/:boundary;
ball._x = /:x_original + (/:x_displacement);
ball._y =/:y_original + (/:y_displacement);

4) Place the movieclip on the stage and place it directly where you want it to be anchored.
5)In frame 1, or whenever the movieclip is beginning, add actionscript in that frame:

/:x_original = getProperty(ball,_x);
/:y_original = getProperty(ball,_y);

6) Determine what x and y displacement you want for randomly placing your graphic. If you decided you want it to displace 5 pixels, then you would add the following line:

/:boundary = 5;



That's it. If you want to control when it will randomly place, and when it will not, obviously you can place a stop() command in frame 1 of the movieclip and tell it to play whenever you want. Also, if you want to displace the graphic in the x and y directions independently, then you can declare a variable called /:boundary_x and /:boundary_y, and then replace the /:boundary variable found in the calculations for /:x_displacement and /:y_displacement.

No comments: