FLASH AS鼠标拖拽与旋转MC教程
网站建设 2021-07-03 14:35www.dzhlxh.cn网站建设
在网上看到某个游戏既要拖拽mc又要旋转mc,拖拽用鼠标事件实现,而旋转需要用shift+鼠标click事件。总觉得太麻烦了。故而希望自己能找到一种只用鼠标就能同时实现拖拽与旋转功能的方法。
结果发现MOUSE_DOWN+MOUSE_UP竟然相当于一次CLICK事件。即每次释放鼠标左键,停止拖拽时,mc会旋转一次,而这个显然不是预期的效果。
于是,开始明白了,那个程序员为什么要添加shift键的侦听了。
可是,不用shift键就不能实现这种功能吗?我开始考虑如何区分MOUSE_DOWN+MOUSE_UP与CLICK.。
方法一:设置时间间隔。时间不太好把握,pass掉。
方法二:用鼠标的相对位置。倘若mc未移动则视为click事件。正解!
复制代码
代码如下:package{
import flash.display .*;
import flash.geom .Point;
import flash.events.*;
public class main extends Sprite{
private var mc:MC;
private var clickOffset:Point;
private var mouseLoc:Point;
public function main(){
mc=new MC();
addChild(mc);
mc.x=200;
mc.y=200;
mc.addEventListener(MouseEvent.CLICK ,rot);
mc.addEventListener(MouseEvent.MOUSE_DOWN,startdrag);
mc.addEventListener(Event.ENTER_FRAME. ,drag);
stage.addEventListener(MouseEvent.MOUSE_UP,stopdrag);
}
private function startdrag(e:MouseEvent ){
mouseLoc=new Point(e.stageX,e.stageY);
clickOffset=new Point(e.stageX-mc.x,e.stageY-mc.y);
}
private function drag(e:Event){
if(clickOffset==null) return;
mc.x=mouseX-clickOffset.x;
mc.y=mouseY-clickOffset.y;
}
private function stopdrag(e:MouseEvent ){
clickOffset=null;
}
private function rot(e:MouseEvent){
if(!mouseLoc.equals(new Point(e.stageX,e.stageY)))return;
mc.rotation+=30;
}
}
}
import flash.display .*;
import flash.geom .Point;
import flash.events.*;
public class main extends Sprite{
private var mc:MC;
private var clickOffset:Point;
private var mouseLoc:Point;
public function main(){
mc=new MC();
addChild(mc);
mc.x=200;
mc.y=200;
mc.addEventListener(MouseEvent.CLICK ,rot);
mc.addEventListener(MouseEvent.MOUSE_DOWN,startdrag);
mc.addEventListener(Event.ENTER_FRAME. ,drag);
stage.addEventListener(MouseEvent.MOUSE_UP,stopdrag);
}
private function startdrag(e:MouseEvent ){
mouseLoc=new Point(e.stageX,e.stageY);
clickOffset=new Point(e.stageX-mc.x,e.stageY-mc.y);
}
private function drag(e:Event){
if(clickOffset==null) return;
mc.x=mouseX-clickOffset.x;
mc.y=mouseY-clickOffset.y;
}
private function stopdrag(e:MouseEvent ){
clickOffset=null;
}
private function rot(e:MouseEvent){
if(!mouseLoc.equals(new Point(e.stageX,e.stageY)))return;
mc.rotation+=30;
}
}
}