---
title: "使用AS3帧代码控制动画"
author: "cuixuxucui"
date: "2011-10-17T14:26:46Z"
tags: []
categories: ["Web前端"]
slug: "as3"
draft: false
lastmod: "2011-10-17T15:23:07Z"
id: 1198409
url: "https://smartblack.iteye.com/blog/1198409"
---

美术同事出了一个资源，大致是这样的：四个角色形象动画，聚在一个台子四周。有一个向左和向右按钮，点击后四个形象分别向对应的方向旋转后将其中一个推到正面，表示当前选中的的角色形象。具体资源是，使用了一个圆形的引导线，每次点击使用逐渐变化的6帧表示这个旋转。4段动画，共计24帧。

尝试一：

我创建了一个代码脚本层，把代码写在第一帧上了。不爽的事情发生了，每次旋转一圈后，这段代码的全局变量就会被重新初始化。。。。。

尝试二：

使用文档类，却发现我这个资源只是库元件。文档类也帮不上我。

尝试三：

额外使用一个MC，将上面的24帧MC元件放在一层中，另外再创建一层放代码，使用引用名字如figureMc来控制这个24帧动画的行为。目前看起来一切正常~~

附代码：

 

//2011.10.17 xu.cui

rotateFigure.stop();//rotateFigure是旋转动画

var beginFramesArray:Array = \[1,7,13,19];//四段动画的起始帧

var endFramesArray:Array = \[6,12,18,24];//四段动画的结束帧

var position:int = 0;//标记箭头点击位置(向右加1，向左减1)

var curEndFrame:int = 0;//当前段的动画开始播放后，在哪一帧结束

var direction\_isNext:Boolean = true;//标记箭头方位(默认向右)

 

pre.addEventListener(MouseEvent.CLICK, preClickHandler);

next.addEventListener(MouseEvent.CLICK, nextClickHandler);

 

function preClickHandler(event:MouseEvent):void{

direction\_isNext = false;

position --;

playMc(position);

trace("position:"+position);

}

 

function nextClickHandler(event:MouseEvent):void{

direction\_isNext = true;

position ++;

playMc(position - 1);//因为起始默认值为0，所以需要减1

trace("position:"+position);

}

 

function figureType():int{

return position % beginFramesArray.length;

}

 

function playMc(posi:int):void{

var remainder:int = posi % beginFramesArray.length;

if(remainder &lt; 0){

remainder += beginFramesArray.length;

}

if(direction\_isNext){

rotateFigure.gotoAndStop(beginFramesArray\[remainder]);

curEndFrame = endFramesArray\[remainder];

}else{

rotateFigure.gotoAndStop(endFramesArray\[remainder]);

curEndFrame = beginFramesArray\[remainder];

}

//trace("remainder:" + remainder + ",curEndFram:" + curEndFrame);

rotateFigure.addEventListener(Event.ENTER\_FRAME, enterFrameHandler);

}

 

function enterFrameHandler(event:Event):void{

//trace("currentFrame:" + rotateFigure.currentFrame);

if(direction\_isNext){

rotateFigure.nextFrame();

}else{

rotateFigure.prevFrame();

}

if(rotateFigure.currentFrame == curEndFrame){

rotateFigure.removeEventListener(Event.ENTER\_FRAME, enterFrameHandler);

}

}