Free ActionScript

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

Player movement – click to move

No Comments »

Mouse player movement example script.

Click to make the player rotate and go to the mouse (click to go):

View Code ACTIONSCRIPT
/**
 * Player Movement - Go to mouse
 * ---------------------
 * 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 _playerSpeed:Number = 10;
 
        // other vars
        private var _destinationX:int;
        private var _destinationY:int;
 
        /**
         * Constructor
         */
        public function Main() 
        {
            createPlayer();
 
            // add listeners
            stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
            stage.addEventListener(MouseEvent.CLICK, mouseHandler);
        }
 
        /**
         * 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
        {            
            _player.x += (_destinationX - _player.x) / _playerSpeed;
            _player.y += (_destinationY - _player.y) / _playerSpeed;
        }
 
        /**
         * Mouse Handlers
         */
        private function mouseHandler(event:MouseEvent):void
        {
            _destinationX = event.stageX;
            _destinationY = event.stageY;
 
            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

Leave a Reply

You must be logged in to post a comment.