ActionScript 3.0: перемещение объекта с задержкой между перемещениями

#flash #actionscript-3 #actionscript #adobe

#flash #actionscript-3 #actionscript #adobe

Вопрос:

Я работаю над игрой, в которой я хочу, чтобы видеоролик перемещался из одного случайного местоположения в другое с паузой между каждым движением. Я написал некоторый код с помощью некоторых руководств, но я не могу заставить его работать так, как я хочу. Я новичок в ActionScript, поэтому, вероятно, я все делаю неправильно. Прямо сейчас все, что делает моя игра, — это пауза на определенное время, а затем объект просто чрезвычайно быстро перескакивает с одного места на другое и не останавливается.

 //movement of searchlight

var i:int;
for (i = 0; i < 5; i  )
{
var startTime = getTimer();

stage.addEventListener(Event.ENTER_FRAME, timeDelay);

function timeDelay(event:Event):void
{
    var timePassed = getTimer();
    if (timePassed - startTime >= 5000)
    {
        moveTo();
    }
}

myObject.x = Math.round(Math.random() * 550);
myObject.y = Math.round(Math.random() * 400);
myObject.rotation = Math.round(Math.random() * 360);

// a counter that counts the current
// frame of the animation
var currentFrameCount:int;
// the total frames in the animation
var totalFrameCount:int = 20;

// the location when the animation starts
var initialX:Number;
var initialY:Number;
// the distance between the initial
// location and the destination
var distanceX:Number;
var distanceY:Number;

// when animation starts
function moveTo():void
{

    var myLocationX = Math.round(Math.random() * 550);
    var myLocationY = Math.round(Math.random() * 400);

    // the destination location 
    var destinationX:Number = myLocationX;
    var destinationY:Number = myLocationY;

    // reset frame count to 0
    currentFrameCount = 0;
    // set initial locations to the
    // current location of myObject
    initialX = myObject.x;
    initialY = myObject.y;
    // find the distance values by finding
    // the difference between initial and destination
    distanceX = destinationX - initialX;
    distanceY = destinationY - initialY;
            // set up rotation
    var initialAngle = myObject.rotation;
    var myAngleStart = Math.atan2(myLocationY-initialY,myLocationX-initialX)/(Math.PI/180);
    var myAngle = myAngleStart   284;
    myObject.rotation = myAngle;

    // set up the enterFrame loop to 
    // animate the animation
    myObject.addEventListener(Event.ENTER_FRAME, animateMoveTo);

    // handling the animation over time;
    function animateMoveTo(evt:Event):void
    {
        // each frame, increment the frame count
        // to move the animation forward
        currentFrameCount  ;
        // if the frame count has not yet reached the
        // final frame of the animation, myObject
        // needs to be moved to the next location
        if (currentFrameCount < totalFrameCount)
        {
            // find the progress by comparing current frame
            // with the total frames of the animation
            var progress:Number = currentFrameCount / totalFrameCount;
            // set myObject's position to include the new
            // distance from the original location as
            // defined by the distance to the destination
            // times the progress of the animation
            myObject.x = initialX   distanceX * progress;
            myObject.y = initialY   distanceY * progress;
            myObject.rotation = initialAngle   myAngle * progress;
        }
        else
        {
            // when the animation is complete, set the
            // position of myObject to the destination
            myObject.x = destinationX;
            myObject.y = destinationY;

            // remove the enterFrame event handler so the 
            // animation ceases to run
            myObject.removeEventListener(Event.ENTER_FRAME, animateMoveTo);
        }
    }
}
}
  

ОБНОВЛЕНИЕ: Вот что я в итоге сделал:

 import com.greensock.TweenLite;

//set random starting location and rotation
myObject.x = Math.round(Math.random() * 550);
myObject.y = Math.round(Math.random() * 400);
myObject.rotation = Math.round(Math.random() * 360);

//create variables
var initialX:Number;
var initialY:Number;
var destinationX:Number;
var destinationY:Number;
var myAngleStart;
var myAngle;

//timer
var timer:Timer = new Timer( 12000 )
timer.addEventListener( TimerEvent.TIMER,rotate );
timer.start();

//function rotate
function rotate( e:TimerEvent ):void{
//set variables for current location
initialX = myObject.x
initialY = myObject.y
//set new destination
destinationX = Math.round(Math.random() * 550);
destinationY = Math.round(Math.random() * 400);
//set rotation
myAngleStart = Math.atan2(destinationY-initialY,destinationX-initialX)/(Math.PI/180);
myAngle = myAngleStart   284;
//rotate towards new destination
TweenLite.to(myObject, 5, {rotation:myAngle, onComplete:moveTo});
}

//function moveTo
function moveTo():void {
TweenLite.to(myObject, 7, {x:destinationX, y:destinationY});
}
  

Комментарии:

1. Точно ли этот код используется в вашем проекте? Я вижу по крайней мере одну проблему с вложенной функцией.

2. Не могли бы вы немного подробнее описать, какого эффекта вы пытаетесь добиться?

3. По сути, объект перемещается из одного случайного местоположения в другое, и его необходимо указывать в направлении, в котором он движется. когда он доберется до нужного местоположения, он должен остановиться, повернуться лицом к следующему случайно сгенерированному местоположению, а затем переместиться туда (и постоянно повторять эти действия). я еще не совсем правильно закодировал часть вращения, в основном я работал над тем, чтобы заставить его перемещаться в одно место, останавливаться, а затем перемещаться в другое и т.д.

4. Спасибо всем, в итоге я использовал комбинацию всех трех ответов. 🙂

Ответ №1:

Вам следует изучить один из многих удобных движков для настройки, таких как TweenLite или Tweener. Они делают такого рода вещи очень простыми.

Комментарии:

1. Код, опубликованный в других ответах, вероятно, очень полезен для людей, которые хотят узнать о том, как выполнять анимацию. Но, учитывая признание того, что я крайне новичок в actionscript и использую некоторый обучающий код. («франкенкодирование», как я это называю.) Я бы настоятельно рекомендовал использовать один из движков анимации, перечисленных здесь. Они действительно достаточно надежны для большинства применений.

2. @прототип 1. Предлагая использовать один из движков анимации, я вообще не пытаюсь получить какой-либо подробный ответ на вопрос, и я согласен, что это очень полезные знания.

Ответ №2:

Хорошо, я немного поработал над этим, и я думаю, что это близко к тому, что вы хотите. Вращение не работает должным образом, но у меня нет времени возиться с этим прямо сейчас. Этот метод сильно зависит от частоты кадров. При использовании этого метода анимации возникнут проблемы, если частота кадров пользователя упадет ниже частоты кадров, на которую у вас установлен фильм. Я установил свою частоту кадров на 30 кадров в секунду. Я думаю, что это может направить вас на правильный путь к улучшению вашего кода, хотя:

     //Declare Globals
var currentFrameCount:int=0;
var totalFrameCount:int = 30;
myObject.x = Math.round(Math.random() * 550);
myObject.y = Math.round(Math.random() * 400);
var destinationX:Number = myObject.x;
var destinationY:Number = myObject.y;
var initialX:Number;
var initialY:Number;
var distanceX:Number;
var distanceY:Number;
var xProg:Number;
var yProg:Number;
var myAngleChange;
var myAngleEnd;
var initialAngle;

var countFrame:int = 0;
var delay:int = 0;

addEventListener(Event.ENTER_FRAME,callDelay);
function callDelay(e:Event){
        countFrame  ;
        delayEvent(delay);
}
//Code to move the object to a random location and give it a random target to move to.
function spawnObject(){
        myObject.rotation = Math.round(Math.random() * 360);//random rotation
        initialAngle = myObject.rotation;
        destinationX = Math.round(Math.random() * 550);//random destination
        destinationY = Math.round(Math.random() * 400);
        currentFrameCount = 0;
        initialX = myObject.x;
        initialY = myObject.y;
        distanceX = destinationX - initialX;//distance between destination and initial
        distanceY = destinationY - initialY;
        initialAngle = myObject.rotation;//buggy rotation code
        myAngleEnd = Math.atan2(destinationY-initialY,destinationX-initialX)/(Math.PI/180);
        myAngleChange = (initialAngle - myAngleEnd)/totalFrameCount;
        xProg = distanceX/totalFrameCount;//amount to increase by each frame
        yProg = distanceY/totalFrameCount;
}


function delayEvent(period){
        if ( (countFrame) >= period){
                removeEventListener(Event.ENTER_FRAME,callDelay);
                timedEvent();
                countFrame=0;
                return;
        }

}


function timedEvent ():void
{
                currentFrameCount = totalFrameCount;
                myObject.x = destinationX;
                myObject.y = destinationY;
                spawnObject();//move the object to a new location and give new destination
                myObject.addEventListener(Event.ENTER_FRAME,moveTo);//add an event listener to move the object around
}

function moveTo(e:Event):void
{
                myObject.rotation  = myAngleChange; //increase rotation by the rotation step value (buggy)
        currentFrameCount  ;
        if (currentFrameCount < totalFrameCount)
        { 
            myObject.x  = xProg;//incrase x by the x step value
            myObject.y  = yProg;//increase y by the y step value
        }
        else
        {
            myObject.removeEventListener(Event.ENTER_FRAME, moveTo);// remvoe this event listener
                        addEventListener(Event.ENTER_FRAME,callDelay);
        }
}
  

Комментарии:

1. Дрожание, вероятно, связано с циклом for

Ответ №3:

Если вы просто хотите перемещать объект с заданными интервалами, просто используйте это

 var timer:Timer = new Timer( 1000 )
timer.addEventListener( TimerEvent.TIMER,moveTo );
timer.start();

function moveTo( e:TimerEvent ):void{
    myObject.x = Math.round(Math.random() * 550);
    myObject.y = Math.round(Math.random() * 400);
}