Answer the question
In order to leave comments, you need to log in
Smooth animation of 30-100 objects in ActionScript 3
I want to make an animation for my Flash game with balloons that fly through the screen when the level is successfully completed.
But it is not possible to do this smoothly and so that the processor does not eat much.
My balloons are movie clips that I randomly resize up and down to give the impression of "different" balloons. I make the movement of the balls using the TweenMax library.
But the result depresses me with its quality.
Here is the piece of code I am using:
public static function randomScale(shape: DisplayObject, ll: Number, ul: Number): void
{
var sc: Number = 1 + Math.random() * ((Math.random() < 0.5) ? 1 : -1);
sc = ((sc < ll) || (sc > ul)) ? 1 : sc;
if (sc != 1)
{
shape.scaleX = sc;
shape.scaleY = sc;
}
}
/**
* Произвести запуск объектов в полет от низа контейнера к верху, можно использовать для оформления прохождения уровня.
*
* @param parent - родительский контейнер внутри которого будут летать объекты.
* @param duration - длительность анимации.
* @param delayMax - максимальная задержка перед анимацией.
* @param deltaX - максимальное отклонение по координате X в лево или право, для придания естественности поведения.
* @param scale - применять изменение масштаба объектов в диапазоне от 0.7 до 1.5.
* @param callback - функция вызываемая по окончанию анимации.
*/
public static function fly(parent: DisplayObjectContainer, shapes: Vector.,
duration: Number, delayMax: Number,
deltaX: uint,
scale: Boolean = false,
callback: Function = null): void
{
// получаем габариты родительского контейнера
var w: uint = parent.width;
var h: uint = parent.height;
var cnt: uint = shapes.length;
// запускаем объекты один за одним
for each (var shape: MovieClip in shapes)
{
// случайное положение объекта
shape.x = Math.round(Math.random() * w);
shape.y = h + 5; // исходно объекты находятся внизу
shape.visible = false;
// изменение масштаба объекта в небольшм диапазоне
if (scale)
{
randomScale(shape, 0.7, 1.5);
}
parent.addChild(shape);
// запускаем анимацию полета
TweenMax.to(shape, duration, // длительность анимации
{delay: delayMax * Math.random(), // произвольная задержка 0...delayMax секунды, что бы выглядело естественно
x: shape.x + (Math.round(Math.random() * deltaX * 2) - deltaX), // точка назначения отличается ± deltaX от исходной
y: -150, // объекты улетают за границу экрана
ease: Linear.easeIn, // объекты летят с линейной скоростью
visible: false, // в конце они становятся невидимыми
onInit: showShape,
onInitParams: [shape],
onComplete: removeShape, // метод для зачистки по окончании анимации
onCompleteParams: [shape]
});
}
function showShape(child: MovieClip): void
{
child.visible = true;
}
/** Зачистка по окончании анимации */
function removeShape(child: MovieClip): void
{
// удаляем объекты из контейнера по окончанию анимации
parent.removeChild(child);
}
}
}
Answer the question
In order to leave comments, you need to log in
Well, in a loop, create movies with a random size and a random x coordinate, then add ENTER_FRAME to each and, accordingly, a function that will randomly change the x coordinate a little in each frame (so that it seems to be shaking from the wind into a light one) and reduce y coordinate so that it flies up. Well, make the frame rate 41 per second. Everything should turn out smoothly and beautifully. You can also animate the ball inside for realism. That he would change shape a little.
There are two tips that will help you, no matter what animation you do, do
not use what is not visible - if you move an object by 10 pixels per second at 100 FPS - every time you mix it by 0.01 - there is no point in this, but the percentage eats.
Let's take a deeper look.
100 objects will blend by 10 pixels. At 100 FPS
you try it, brakes, goodbye 100 FPS. Cycle...
Now let's not mix them up for invisible distances. Also, we will give everyone a certain starting “offset”.
As a result, only 10 objects will be shifted for each tick. In the next tick - another 10.
For the "visible" tick - that's it.
Statement - if you break the animation into parts, and do not animate all the objects - this will raise the FPS
. Raising the FPS will smooth out possible object shift jumps.
And - the faster it works - the faster it works ...
I tried this technology a lot in my time on shadow-mapping (through textures) - you need to update the cube. Here is a complete update of 6 faces slowed down. And if there are only two faces in a teak, it's fine. And raising the FPS did not make it possible to notice that some facets exist a little at the wrong time
So far, all experiments with smoothness have come down to the following: if you make the “flight” time of the balls across the entire screen for more than 5 seconds, for example 10, then it turns out smoothly, but very slowly :(, the player will quickly start cursing such balls.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question