flash actionscript3.0 元件跟随鼠标

目标是一个元件跟随鼠标,可以按鼠标点击的线路走

主要用到三角函数

圆函数

                       sun.x=sun.x+Math.cos(angle)*5;
                     sun.y=sun.y+Math.sin(angle)*5;


求弧度函数

angle=Math.atan2(dy,dx);


求出角度,然后设置前进速度


package 
{

	import flash.display.Sprite;
	import flash.events.*;
	import flash.geom.*;
	import flash.filters.*;
	import flash.display.DisplayObject;

	public class yuangan extends Sprite
	{
		private var sun,earth,moon:Sprite=new Sprite();//创建容器
		private var centerX:Number=stage.stageWidth/2;
		private var centerY:Number=stage.stageHeight/2;
		private var k,dx,dy,angle:Number=0;
		private var b,dist:Number=0;
		private var point:Point=new Point();
		private var plist:Array=new Array();
		public function yuangan()
		{
			//画一个小太阳
			sun=new Sprite();
			addChild(sun);
		    sun.graphics.beginFill(0xffcc00);
		    sun.graphics.drawCircle(0,0,10);
		    sun.graphics.endFill();			
			
			//太阳位置在舞台中间
			sun.x=centerX;
			sun.y=centerY;
			sun.z=0;			
			//对太阳使用模糊
			sun.filters=[new BlurFilter(5,5,BitmapFilterQuality.HIGH)];
						
			point.x=sun.x;
			point.y=sun.y;  
			//鼠标点中后停住
			sun.addEventListener(MouseEvent.MOUSE_DOWN,clearStep);
			//倾听舞台鼠标点击
			stage.addEventListener(MouseEvent.MOUSE_DOWN,Mousedown);
           //加入帧事件
			addEventListener(Event.ENTER_FRAME,Run);
		}
		public function clearStep(e:Event):void{
			 plist=new Array();
			 point.x=sun.x;
			 point.y=sun.y; 
			 e.stopPropagation();
		}
		public function Run(e:Event):void{
			   dx = point.x-sun.x;
               dy = point.y-sun.y;
			   //如果小于5,设置为目标点
			   if(Math.abs(dx)<5&&Math.abs(dy)<5)
			   {
				     sun.x=point.x;
			         sun.y=point.y;  
				}else{
				  	 sun.x=sun.x+Math.cos(angle)*5;
			         sun.y=sun.y+Math.sin(angle)*5;	
				}
			if(plist.length>0&&sun.x==point.x&&sun.y==point.y)
			{
			   point=plist.shift();
			   dx = point.x-sun.x;
               dy = point.y-sun.y;
			   /*
			   //根据三角函数求出弧度也是角度
			   ball.x=centerX+Math.cos(angle)*radius;
			   ball.y=centerY+Math.sin(angle)*radius
			   angle = Math.atan2(dy,dx)*180/Math.PI;
			   */
			   angle=Math.atan2(dy,dx);
			}


		}
		/*
		记录鼠标位置
		*/
		public function Mousedown(e:Event):void{
			var p:Point=new Point();
			p.x=stage.mouseX;
			p.y=stage.mouseY;
			plist.push(p);
			if(plist.length>5)
			{
                plist.pop();
				plist.pop();
				plist.push(p);				
             }		    
			  
		}
	}
}



阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭