I am trying to take a movieclip inside of an AS3 file and make it rotate smoothly when someone clicks and drags it. I know my code is close but right now instead of dragging, it moves a fixed distance on click. You can see the sample here: http://server.iconixinc.com/drag/
and here is my code
const TO_DEGREE:Number = 180/Math.PI;
addEventListener(MouseEvent.MOUSE_DOWN, startRotate, true);
addEventListener(MouseEvent.MOUSE_UP, stopRotate, true);
var maxRotSpeed:Number = .1;
var rotScale:Number = 0.2;
function startRotate(e:MouseEvent):void
{
var dx:int = stage.mouseX - myMc.x;
var dy:int = stage.mouseY - myMc.y;
var rot:Number = Math.atan2(dy, dx) * TO_DEGREE;
var drot = rot - myMc.rotation;
if(drot < -180) drot += 360;
if(drot > 180) drot -= 360;
drot *= rotScale;
myMc.rotation += drot;
}
function stopRotate(e:MouseEvent) {
myMc.stopDrag();
}
Any thoughts on what I might be doing wrong?
You aren't actually using the drag and drop features of AS3, so you don't need the call to stopDrag
. You're actually very close, you just want to move your code into a move listener:
const TO_DEGREE:Number = 180/Math.PI;
addEventListener(MouseEvent.MOUSE_DOWN, startRotate, true);
addEventListener(MouseEvent.MOUSE_UP, stopRotate, true);
var maxRotSpeed:Number = .1;
var rotScale:Number = 0.2;
function startRotate(e:MouseEvent):void
{
// you want the calculation to occur whenever the mouse moves,
// not just when the mouse button is clicked
addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
function onMouseMove(e:MouseEvent):void {
var dx:int = stage.mouseX - myMc.x;
var dy:int = stage.mouseY - myMc.y;
var rot:Number = Math.atan2(dy, dx) * TO_DEGREE;
var drot = rot - myMc.rotation;
if(drot < -180) drot += 360;
if(drot > 180) drot -= 360;
drot *= rotScale;
myMc.rotation += drot;
}
function stopRotate(e:MouseEvent) {
// instead of calling stopDrag, you simply remove the move listener
removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.