Flash-鼠标,键盘事件

今天咱来看下Flash的鼠标和键盘事件。。
先放Demo:

这个Demo实现的功能很简单,鼠标放到小球上,小球透明度会变成0.5,鼠标移开会恢复到1,按住鼠标可以拖动小球。按下键盘的上下左右键可以移动小球。
下边咱慢慢来看下,显示fla文档下的代码:

//设置舞台属性,坐上角对齐,不拉伸
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

//new一个Role类的实例出来,并居中显示
var mRole = new Role(stage);
addChild(mRole);
setCenter(mRole);

function setCenter(obj:DisplayObject):void{
	obj.x = (stage.stageWidth - obj.width)/2;
	obj.y = (stage.stageHeight - obj.height)/2;
}

//onResize事件
stage.addEventListener(Event.RESIZE,mResize);
function mResize(e:Event):void{
	//场景大小变化时的操作
}


然后是这个Role类:

package {
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.geom.Rectangle;
	import flash.events.*;

	public class Role extends Sprite {
		private var mStage:Stage;//根场景的stage
		private var mSpeed:int = 10;//移动速度

		public function Role(stage:Stage):void {
			mStage = stage;
			//绘制形状
			draw();
			//添加事件监听
			addEventListeners();
		}
		private function draw():void {
			with (graphics) {
				beginFill(0x999999);
				lineStyle(1, 0x000000);
				drawCircle(0, 0, 10);
				endFill();
			}
		}
		private function addEventListeners():void{
			addEventListener(MouseEvent.MOUSE_OVER,mOver);//鼠标 hover
			addEventListener(MouseEvent.MOUSE_OUT,mOut);//鼠标 out
			addEventListener(MouseEvent.MOUSE_DOWN,mDown);//鼠标 down,PS:down和click是有区别的,click包含了down和up2个事件
			mStage.addEventListener(MouseEvent.MOUSE_UP,mUp);
			mStage.addEventListener(KeyboardEvent.KEY_DOWN, mKeyDown);//Keyboard事件
		}
		private function mOver(e:MouseEvent):void{
			alpha = 0.5;
		}
		private function mOut(e:MouseEvent):void{
			alpha = 1;
		}
		private function mDown(e:MouseEvent):void{
			startDrag(true,new Rectangle(0,0,mStage.stageWidth,mStage.stageHeight));
		}
		private function mUp(e:MouseEvent):void{
			stopDrag();
		}
		private function mKeyDown(e:KeyboardEvent):void{
			if (e.keyCode==37) {
				x -= mSpeed;
			} else if (e.keyCode == 39) {
				x += mSpeed;
			} else if (e.keyCode == 38) {
				y -= mSpeed;
			} else if (e.keyCode == 40) {
				y += mSpeed;
			}
			checkWall(new Rectangle(0,0,mStage.stageWidth,mStage.stageHeight));
		}
		//四周边界碰撞修正
		private function checkWall(rect:Rectangle):void{
			if(x < =rect.left){
				x = rect.left;
			}
			if(x >= rect.right){
				x = rect.right;
			}
			if(y < =rect.top){
				y = rect.top;
			}
			if(y >= rect.bottom){
				y = rect.bottom;
			}
		}
	}
}

Some Related Posts

  • 2009/04/06 -- (1)

No comments yet.


:zhuang :xizao :wuwu :wenhao :wc :touxiang :shuaya :shuajian :shengtian :paopao :no :meinv :maonv :loveu :leilei :kua :jrjr :dahan :chi :chaocai :byebye


郑重声明:资讯 【Flash-鼠标,键盘事件】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——