单击并拖动框架AS3

时间:2011-03-15 17:52:34

标签: actionscript-3 animation drag

我有一个逐帧动画。我希望能够来回拖动舞台并遍历动画。即我想点击并从左向右拖动以使动画向前和从右向左移动以使动画向后移动。

我将如何实现这一目标?

我假设在计算鼠标位置和遍历到正确的帧时会涉及一些数学,但我该怎么做?

2 个答案:

答案 0 :(得分:2)

在这里(编辑版)

import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.display.Sprite;

var clickedMouseX:int;
var clickedFrame:uint;
var backgroundClip:Sprite = getChildByName("background") as Sprite;
var clip:MovieClip = getChildByName("animation") as MovieClip;
clip.stop();
clip.mouseEnabled = false;

backgroundClip.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
backgroundClip.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);


function onMouseDown(event:MouseEvent):void
{
    backgroundClip.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
    clickedMouseX = backgroundClip.mouseX;
    clickedFrame = clip.currentFrame;
}

function onMouseUp(event:MouseEvent):void
{
    backgroundClip.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}

function onMouseMove(event:MouseEvent):void
{   
    var delta:int = backgroundClip.mouseX - clickedMouseX;
    var wantedFrame:uint = (clickedFrame + delta * clip.totalFrames / backgroundClip.width) % clip.totalFrames;
    while (wantedFrame < 1)
    {       
        wantedFrame += clip.totalFrames;
    }
    clip.gotoAndStop(wantedFrame);
}

干杯!

答案 1 :(得分:0)

应该将拖动区域的长度映射到时间轴的长度:

stage.addEventListener(MouseEvent.MOUSE_MOVE, updateAnimation);
function updateAnimation(event:MouseEvent):void {
    animation.gotoAndStop(Math.floor(mouseX/stage.stageWidth * animation.totalFrames));
}

这是评论版:

stage.addEventListener(MouseEvent.MOUSE_MOVE, updateAnimation);
function updateAnimation(event:MouseEvent):void {
    //take the ratio between the mouse position and stage width -> //a number from 0.0 to 1.0
    var mouseRatio:Number = mouseX/stage.stageWidth; 
    //'scale'/multiply that number to fit the animation frames  -> from a maximum of 1.0 to animation's total frames
    //also, we 'round down' because we need an integer for the frame number, not a fractional number
    var frame:int = Math.floor(mouseRatio * animation.totalFrames);
    animation.gotoAndStop(frame);
}

此外,并非MOUSE_MOVE每秒触发几帧。您可以在ENTER_FRAME上更新,因为您提到了拖动,您还可以使用一个变量来跟踪鼠标是否被按下或释放:

var mousePressed:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, togglePressed);
stage.addEventListener(MouseEvent.MOUSE_UP, togglePressed);
stage.addEventListener(Event.ENTER_FRAME, update);

function togglePressed(event:MouseEvent):void {
    mousePressed = event.type == MouseEvent.MOUSE_DOWN;
}
function update(event:Event):void {
    if(mousePressed) animation.gotoAndStop(Math.floor(mouseX/stage.stageWidth * animation.totalFrames));
}

HTH