ActionScript 3.0 Particle Systems #6: Particle Attraction

More ActionScript… This time we’re attracting the particles towards the mouse cursor when the distance between them is low enough… Looks alright, just a kinda fun effect & dead simple to code.

Source code and flash files on the flipside…

Flash File (ActionScript 3.0) Code:

// Loop to shove a hundred particles on the stage
for (var loop:uint = 0; loop < 100; loop++) {
 
	// Define initial home locations for the particles
	var tempHomeX = Math.random() * stage.stageWidth;
	var tempHomeY = Math.random() * stage.stageHeight;
 
	// Instantiate the particle at the given location
	var particle:Attraction = new Attraction(tempHomeX, tempHomeY);
 
	// Set particle alpha and scale
	particle.alpha = (Math.random() * 0.7) + 0.3;
	particle.scaleX = particle.scaleY = (Math.random() * 0.7) + 0.3;
 
	// Display the particle on the stage
	addChild(particle);
}

ActionScript 3.0 Attraction Class Code:

package
{
	import flash.display.MovieClip;
	import flash.events.Event;
 
	public class Attraction extends MovieClip
	{
		// Per object instance variables
		var homeX:Number;
		var homeY:Number;
		var distance:Number;
 
		// Class-wide variables
		static var attractionThreshold = 150;
		static var speedTo:Number = 4;
		static var speedAway:Number = 10;
 
		// Constructor
		function Attraction(homeXValue:Number, homeYValue:Number):void
		{
			// Set our home locations using values passed to the constructor
			this.homeX = homeXValue;
			this.homeY = homeYValue;
 
			// Set our particles to be at their home locations by default
			this.x = homeXValue;
			this.y = homeYValue;
 
			// Bind each particle to update once per frame
			this.addEventListener(Event.ENTER_FRAME, updateParticle);
		}
 
		private function updateParticle(e:Event):void
		{
			// Calculate the distance between our mouse cursor and the particle
			this.distance = Math.sqrt( Math.pow((this.parent.mouseX - this.homeX), 2) + Math.pow((this.parent.mouseY - this.homeY), 2) );
 
			// If it's less than the attraction threshold start moving the particle towards the mouse cursor		
			// Switch the "<=" to ">=" for an interesting effect ;)
			if (this.distance <= attractionThreshold) {
 
				this.x += (this.parent.mouseX - this.x) / speedTo;
				this.y += (this.parent.mouseY - this.y) / speedTo;
			}
			else // Otherwise let it return to its original location
			{
				this.x += (this.homeX - this.x) / speedAway;
				this.y += (this.homeY - this.y) / speedAway;
			}
 
		} // End of updateParticle function
 
	} // End of class
 
} // End of package

As ever, Adobe Flash CS4 files for the above can be found: here.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.