如何设置弹性跟随鼠标对象的持续时间?

时间:2013-06-29 19:10:35

标签: actionscript-3 flash

我正在尝试制作弹性跟随鼠标。一切都很好。但唯一的问题是:我不希望它长时间反弹。我想设置持续时间只能反弹1秒。这该怎么做 ? 这是我使用的As3脚本:

var distx_L     = 0;
var disty_L     = 0;
var momentumx_L = 0;
var momentumy_L = 0;
var easing_L = 5;


stage.addEventListener(Event.ENTER_FRAME,elastic_follow)
function elastic_follow(event:Event):void {


    distx_L = myball.x - mouseX;
    disty_L = myball.y - mouseY;
    momentumx_L -= distx_L / easing_L;  
    momentumy_L -= disty_L /easing_L; 

    // dampen the momentum a little (ELASTIC)
    momentumx_L*= 0.90;
    momentumy_L *= 0.90;


    myball.x += momentumx_L-15;
    myball.y += momentumy_L;

}

1 个答案:

答案 0 :(得分:0)

应该调整你的价值观。我建议将0.90作为变量提取,以便您可以更轻松地调整它:

var distx_L:Number     = 0;
var disty_L:Number     = 0;
var momentumx_L:Number = 0;
var momentumy_L:Number = 0;
var easing_L:Number = 1;
var ease:Number = 0.5;

stage.addEventListener(Event.ENTER_FRAME,elastic_follow)
function elastic_follow(event:Event):void {


    distx_L = myball.x - mouseX;
    disty_L = myball.y - mouseY;
    momentumx_L -= distx_L / easing_L;  
    momentumy_L -= disty_L /easing_L; 

    // dampen the momentum a little (ELASTIC)
    momentumx_L*= ease;
    momentumy_L *= ease;


    myball.x += momentumx_L;
    myball.y += momentumy_L;

}

如果要在多个剪辑上使用此类行为,您可能希望为每个剪辑赋予弹性和缓动变量。这是一种懒惰的方法:

myball.mx = myball2.mx = 0;//mx for momentum on x axis
myball.my = myball2.my = 0;//my for momentum on x axis
myball.k = 4;//k for elasticity
myball.ease = .75;//ease for the final ease
myball2.k = 6;
myball2.ease = .8;

stage.addEventListener(Event.ENTER_FRAME,elastic_follow)
function elastic_follow(event:Event):void {
    elasticToPos(myball,mouseX-myball.width,mouseY);
    elasticToPos(myball2,mouseX+myball.width,mouseY);
    //elasticToPos(myball2,myball.x+myball.width*2,myball.y);//you can also play with this - have the second clip chase the first rather than the mouse
}

function elasticToPos(clip:MovieClip,targetX:Number,targetY:Number):void{
    var dx:Number = clip.x - targetX;
    var dy:Number = clip.y - targetY;
    clip.mx -= dx / clip.k;
    clip.my -= dy / clip.k;
    clip.mx *= clip.ease;
    clip.my *= clip.ease;
    clip.x += clip.mx;
    clip.y += clip.my;
}

请注意,我为两个剪辑设置了不同的弹性(k)和缓和值,因此它们的行为略有不同。正如我之前提到的,使用这些值可以获得理想的效果。

作为旁注,动态添加变量到动态MovieClip类不是最佳做法。您应该为Sprite创建子类,并为其添加缓动/弹性变量和更新方法。