Free ActionScript

Flash AS2 & AS3 Tutorials, Game Code, Effects, Source Files & Sample Downloads

Simple Physics

Very simple flash physics in AS3. This script creates a ball and makes it bounce around in a container, changing direction when a wall is hit.

View Code ACTIONSCRIPT
/**
 * Simple Physics
 * ---------------------
 * VERSION: 1.1
 * DATE: 11/21/2010
 * AS3
 * UPDATES AND DOCUMENTATION AT: http://www.FreeActionScript.com
 **/
package com.freeactionscript
{
	import flash.display.DisplayObjectContainer;
	import com.freeactionscript.Ball;
	import flash.events.Event;
 
	public class SimplePhysics
	{
		// reference to container (stage, movieclip or sprite)
		private var _canvas:DisplayObjectContainer;
 
		// ball object
		private var _ball:Ball;
 
		// boundries
		private var _minX:int;
		private var _minY:int;
		private var _maxX:int;
		private var _maxY:int;
 
		/**
		 * Constructor
		 * @param	$canvas	Takes DisplayObjectContainer (MovieClip, Sprite, Stage) as argument
		 */
		public function SimplePhysics($canvas:DisplayObjectContainer)
		{
			trace("SimplePhysics");
 
			_canvas = $canvas;
 
			setBoundries(_canvas);
			createBall(_canvas);
			enable();
		}
 
		/**
		 * Creates ball
		 */
		private function createBall($container:DisplayObjectContainer):void
		{
			// get random number between -10 and 10
			var newRandomX:Number = Math.random() * 10 - 10;
			var newRandomY:Number = Math.random() * 10 - 10;
 
			//Ball usage: new Ball(x, y, velocity X, velocity Y);
			_ball = new Ball(150, 200, newRandomX, newRandomY);
			$container.addChild(_ball);
		}
 
		/**
		 * Enables physics engine
		 */
		private function enable():void
		{
			_canvas.addEventListener(Event.ENTER_FRAME, update);
		}
 
		/**
		 * Disables physics engine
		 */
		public function disable():void
		{
			_canvas.removeEventListener(Event.ENTER_FRAME, update);
		}
 
		/**
		 * Sets container boundries
		 */
		public function setBoundries($container:DisplayObjectContainer):void
		{
			_minX = 0;
			_minY = 0;
			_maxX = $container.width;
			_maxY = $container.height;
		}
 
		/**
		 * Update function that updates ball
		 * @param	$event
		 */
		private function update($event:Event):void 
		{
			// Check X
			// Check if we hit top
			if (((_ball.x - _ball.width / 2) < _minX) && (_ball.velocityX < 0))
			{
			  _ball.velocityX = -_ball.velocityX;
			}
			// Check if we hit bottom
			if ((_ball.x + _ball.width / 2) > _maxX && (_ball.velocityX > 0))
			{
			  _ball.velocityX = -_ball.velocityX;
			}
 
			// Check Y
			// Check if we hit left side
			if (((_ball.y - _ball.height / 2) < _minY) && (_ball.velocityY < 0))
			{
			  _ball.velocityY = -_ball.velocityY
			}
			// Check if we hit right side
			if (((_ball.y + _ball.height / 2) > _maxY) && (_ball.velocityY > 0))
			{
			  _ball.velocityY = -_ball.velocityY;
			}
 
			// update ball position
			_ball.x += _ball.velocityX;
			_ball.y += _ball.velocityY;
		}
	}
}
Download Fla Sample

Download Fla Sample

Find out how to add friction in the next example.

FreeActionScript’s New Look

Updated WordPress to the newest version, along with a new look. Hope you like it!

This also fixed issues with comments. You can now use breaks in your comments, as well as code tags to wrap your code.

Note: If you’re having issues with the site (if it looks broken), please clear your browser’s cache.

Draw Box Class

By request, here is a simple box drawing class. Click and drag to draw box based on mouse position.

This can be used as an object selecting mechanism in games to select multiple objects at the same time.

Click and drag to draw box

View Code ACTIONSCRIPT
/**
 * Draw Box class
 * ---------------------
 * VERSION: 1.0
 * DATE: 11/14/2010
 * AS3
 * UPDATES AND DOCUMENTATION AT: http://www.FreeActionScript.com
 **/
package com.freeactionscript
{
	import flash.display.DisplayObjectContainer;
	import flash.events.MouseEvent;
	import flash.display.Sprite;
	import flash.events.Event;
 
	public class Box extends Sprite
	{
		private var _canvas:DisplayObjectContainer;
		private var _startX:Number;
		private var _startY:Number;
		private var _endX:Number;
		private var _endY:Number;
 
		public function Box($canvas:DisplayObjectContainer, $startX:Number, $startY:Number)
		{			
			_canvas = $canvas;
			_startX = $startX;
			_startY = $startY;
			_endX = _canvas.mouseX;
			_endY = _canvas.mouseY;
 
			_canvas.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMoveHandler);
			_canvas.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			_canvas.addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
		}
 
		private function onMouseMoveHandler(event:MouseEvent):void
		{
			_endX = _canvas.mouseX;
			_endY = _canvas.mouseY;
		}
 
		private function onMouseUpHandler(event:MouseEvent):void 
		{
			_canvas.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMoveHandler);			
			_canvas.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			_canvas.removeEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
		}
 
		private function onEnterFrameHandler(event:Event):void 
		{
			graphics.clear();
			graphics.lineStyle(2, 0x88B1CC);
			graphics.moveTo(_startX, _startY);
			graphics.beginFill(0x88B1CC, .25);
			graphics.lineTo(_endX, _startY);
			graphics.lineTo(_endX, _endY);
			graphics.lineTo(_startX, _endY);
			graphics.lineTo(_startX, _startY);
			graphics.endFill();
		}
	}
}
Download Fla Sample

Download Fla Sample

Player Movement – Mouse follow with Easing

Another player movement script: click and hold mouse follow with easing.

Click and hold to make the player follow the mouse:

View Code ACTIONSCRIPT
/**
 * Player Movement - Follow Mouse on click with Easing
 * ---------------------
 * VERSION: 1.0
 * DATE: 9/23/2010
 * AS3
 * UPDATES AND DOCUMENTATION AT: http://www.FreeActionScript.com
 **/
package  
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
 
    public class Main extends MovieClip
    {        
        // player
        private var _player:MovieClip;
 
        // player settings
        private var _speed:Number = .1;
        private var _speedCurrent:Number = 0;
        private var _speedMax:Number = .1;
        private var _acceleration:Number = .01;
        private var _decay:Number = .90;
 
        // other vars
        private var _newDestinationX:int;
        private var _newDestinationY:int;
        private var _destinationX:int;
        private var _destinationY:int;
 
        private var _mouseClicked:Boolean = false;
 
        /**
         * Constructor
         */
        public function Main() 
        {
            createPlayer();
 
            // add listeners
            stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
            stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
            stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
        }
 
        private function onMouseDownHandler(e:MouseEvent):void 
        {
            _mouseClicked = true;
        }
 
        private function onMouseUpHandler(e:MouseEvent):void 
        {
            _mouseClicked = false;
        }
 
        /**
         * Creates player
         */
        private function createPlayer():void
        {
            _destinationX = stage.stageWidth / 2;
            _destinationY = stage.stageHeight / 2;
 
            _player = new Player();
            _player.x = stage.stageWidth / 2;
            _player.y = stage.stageHeight / 2;
            stage.addChild(_player);
        }
 
        /**
         * EnterFrame Handlers
         */
        private function enterFrameHandler(event:Event):void
        {            
            if (_mouseClicked)
            {
                _destinationX = stage.mouseX;
                _destinationY = stage.mouseY;
 
                if (_speedCurrent < _speedMax)
                {
                    _speedCurrent += _acceleration;
                }
            }
            else
            {
                if (_speedCurrent > 0.01)
                {
                    _speedCurrent *= _decay;
                }
                else
                {
                    _speedCurrent = 0;
                }
            }
 
 
 
            _player.x += (_destinationX - _player.x) * _speedCurrent;
            _player.y += (_destinationY - _player.y) * _speedCurrent;
 
            rotatePlayer();
        }
 
        private function rotatePlayer():void
        {
            var radians:Number = Math.atan2(_destinationY - _player.y, _destinationX - _player.x);
            var degrees:Number = radians / (Math.PI / 180) + 90;
            _player.rotation = degrees;
        }
 
    }
 
}
Download Fla Sample

Download Fla Sample