Restrict max speed in tweenmax - actionscript-3

I'm developing game in Flash and I need to move my movie-clips in a wrap-round way across the screen.
For this I m using Tweenmax.to() function provided by greensock.
The function takes 'time' and 'distance' as parameters and applies accleration and deaccleration for the motion itself.
However this takes max-speed of the motion beyond what I want.
Is there a way I could set the max-speed for the motion as well?

I do not think you can control the acceleration manually, but to slow speed down you can either set higher value of time:
say, from
TweenMax.to(mc, 2, {x:65, y:117});
to
TweenMax.to(mc, 4, {x:65, y:117});
Or use another type of easing - every of them contains its own set of acceleration.
There are a lot of them, you could try to find appropriate one.
There is an interactive demo, try playing with different easing functions.

Related

Is there a way to have smooth/subpixel motion without turning on smoothing on graphics?

I'm creating this 2D, pixel art game. When the camera follows the player (it uses easing), on the final approach, the position gets several subpixel adjustments.
If I have smoothing ON (on my graphic assets), the graphics look good (sharp. it's pixel art) but the subpixel motion is jerky/jumpy.
If I have smoothing OFF, the subpixel motion is smooth, but the pixel art graphics look blurry.
I'm using Flash player v21. I've tried this with Starling and with Flash's display list.
You have a pixelated object that is moving in increments of less than the pixel size, but you don't want to restrict your mathematical easing to integers, or even worse, factors of 8 or what have you. The solution I am using in my project for this exact issue is posted below (I just got it working last week!)
Concept
create a driver that is controlled by the easing using floating point numbers.
Allow this driver to then control where the actual display object is rendered. We can use a constraint to only allow the display object to render on your chosen resolution.
Code Example
// you'll put these lines or equivalent in the correct spots for your particular needs.
// SCALE_UP will be your resolution control. If your pixels are 4 pixels wide, use 4.
const SCALE_UP: int = 4;
var d:CharacterDriver = new CharacterDriver();
var c:Character = new Character();
c._driver = d; // I've found it useful to be able to reference the driver
d._drives = c; // or the thing the driver drives via the linked object.
// you don't have to do this.
then when you are ready to do your easing of the driver:
function yourEase(c:Character, d:CharacterDriver):void{
c.x = Math.ceil(d.x - Math.ceil(d.x)%SCALE_UP);//this converts a floating point number into a factor of SCALE_UP
c.y = Math.ceil(d.y - Math.ceil(d.y)%SCALE_UP);
Now this will make your character move around 4 pixels at a time, but still be able to experience easing!
The bit with the modulo (%) operator is the key. For instance, 102-102%4 = 100. 103-103%4 = 100. 104-104%4 = 104.
In case anyone is confused by that, look at what 102%4 does: 4 goes into 102 25 times with a remainder of 2. so 102%4 = 2. Then 102 - 2 = 100.
In your case, since the "camera" is following the player (i.e. the background is moving, right?) then you really need to apply drivers to everything in the background instead, but it is basically the same idea.
Hope this helps.
since you specifically mentioned the "final approach" i think your problem comes from the fact that the easing equations puts your graphics at fractional coordinates, especially while getting closer to the target, but you should also notice it during the rest of the animation.
depending on the easing "engine" that you're using you should be able to set a "round values" flag, so all the coordinates set will be integer values and not fractional
if that's not possible, find a way in your display objects to round the x and y values every time they change

How to replace Mutiple Timers with TweenLite delayedCall or ENTER_FRAME event?

Hey everyone so I have a lot of timers in my game to be specific around 8 timers. They all control different Movie clip objects that appear on the stage at different times. I also change the timers in my difficulty update function. Now I have read a lot to understand that Timers do cause lag and decrease the performance. I am creating this game using AS3 Adobe AIR for Android devices. My game seems to freeze for half a second every second which I believe is do to the timers as well as the garbage collector. Either way I was wondering if I remove all these timers and instead replace them with TweenLite TweenLite.delayedCallfuncion if it would dramatically increase performance. I Have tried this on one of my old timers that i removed and replaced with the tweenlite function and it seems to be working just fine but not sure if this is the correct way of doing it here is how i have it set up in my constructor:
TweenLite.delayedCall(6.0, addWatch);
and the addWatch function:
private function addWatch():void
{
TweenLite.delayedCall(6.0, addWatchTimer);
var newWatch:mcWatchTimer = new mcWatchTimer();
stage.addChild(newWatch);
aWatchTimerArray.push(newWatch);
//Start screen sound
watchSoundChannel;
watchSound = new watch();
watchSoundChannel = watchSound.play(0, 9999);
}
this seems to loop it without me having to attach an ENTER_FRAME Eveent listener to it. But not sure if this would be wise since I want to be able to change the delayedCall in my difficulty update to a faster time interval.
Any feedback on the situation would be appreciated. Hope I made enough sense.

Html Canvas - Translate, Rotate, Clip - Faster restores with using context.restore

After asking a question regarding animation speed a few days ago, the stackoverflow gang once again solved my problem. However, this has led to another question. [The more you know, the more you realise you don't know.]
Basically the fewer state changes to my canvas, the faster things will go. If I am just changing the fillStyle, then using ctx.save and ctx.restore is overkill, as all states are restored. Overkill = Slow. Instead just keep the oldvalue of fillStyle somewhere and put just that back in once you have finished.
So how do you do this for ctx.translate(x, y), ctx.rotate(angle) and ctx.clip()?
How can I restore these guys to their states before my changes WITHOUT having to use ctx.restore?
Your can untransform by using negative values.
ctx.translate(100,100);
// draw lots of stuff
ctx.translate(-100,-100);
ctx.scale(.75,.50);
// draw stuff
ctx.scale(-.75,-.50);
ctx.rotate(Math.PI/4);
// draw stuff
ctx.rotate(-Math.PI/4);
If you do multiple transforms, you must undo them in reverse order
ctx.translate(100,100);
ctx.scale(.75,.50);
ctx.rotate(Math.PI/4);
// draw lots of stuff
ctx.rotate(-Math.PI/4);
ctx.scale(-.75,-.50);
ctx.translate(-100,-100);
But when translating (moving) a few items, it's faster to use an offset instead of a transform.
strokeRect(20+100,20+100,50,30);
fillRect(20+100,20+100,50,30);
Clipping is semi-permanent so you must save/restore the entire context state to undo clip:
context.save();
// define a clipping path
context.clip();
// draw stuff
context.restore();
Transforms are done using a transformation matrix. Canvas gives you access to that matrix using the context.setTransform method.
scaleX=.75;
scaleY=.50;
skewX=0;
skewY=0;
translateX=100;
translateY=100;
context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
// draw stuff
context.setTransform(-scaleX, -skewX, -skewY, -scaleY, -translateX, -translateY);
To also set the matrix for rotation, you must set a combination of the scale & skew values like this:
var radianAngle=Math.PI/4;
var cos=Math.cos(radianAngle);
var sin=Math.sin(radianAngle);
context.setTransform(cos,sin,-sin,-cos,0,0);
// draw stuff
context.setTransform(-cos,-sin,sin,cos,0,0);
To do rotation along with other transforms, just add the rotation values to the scale and skew values.
context.setTransform(scaleX+cos, skewX+sin, skewY-sin, scaleY-cos, translateX, translateY);
// draw stuff
context.setTransform(-scaleX-cos, -skewX-sin, -skewY+sin, -scaleY+cos, -translateX, -translate);
Just to correct the assumption of the question :
False : • The whole context state is saved/restored when using save()/restore() methods.
Let's be modest : An idea that comes to mind in 30 seconds is most likely to be found (and improved) by the developers of major Browsers. So truth is :
True : • Saving the context does almost nothing, and restore applies only on what just occurred.
If in doubt, you can look at the code, but it takes quite some time to be familiar with it (i did it with webKit's canvas => confirmed for this one ).
But it's much easier to look at the various jsperf made on the subject : they show that the gain when hand-saving/restoring one or two properties is moderate to small ==> only what changes is restored.
When hand-saving/restoring more things, then save and restore becomes faster because of Javascript's overhead.
(http://jsperf.com/save-restore-vs-translate-twice/4)
Another thing : talking about 'overkill' seems very exaggerated. Not only because, as seen before, context's save might be faster, but also because, best win is 2X, so we are talking about proudly taking 2ns instead of 4ns for the save. This has to be compared to the time taken for the draw, and might very well not be worth it.
Two last things :
• the bug risk induced by manually saving/restoring ('oops ! i forgot to restore that in that function !').
• the rounding errors that might occur (scale(x,x) => then scale(1/x, 1/x) )
In fact you can save time with no risk is by :
1) batching commands : whenever possible (it all depends on your app, really), batch all commands that expects a given context state.
2) similarly, you can define conventions/rules that prevents you to save/restore the context. For instance : 'always set fillStyle just before filling'. This way you never have to worry about current fillSyle. What you can do here also greatly depends on your app (and wether it's using external APIs or not), but can save a great deal of time for numerous draws.
So my advice would be to use the manual save/restore only for obvious simple case (ex: you just change globalAlpha), and to use conventions/rules to reduce the context state changes to a minimum.

Moving text across screen smoothly

For a long time I've been searching for a solution to this problem, so I decided to post a tread instead when the search didn't clarify anything.
I have a textfield that is supposed to move across the screen. I've solved this by adding a speed to its x-value dynamically through an "enter-frame function". However, the movement is very "laggy" and consists of sudden "jumps" in the movement. I've tried a couple of possible solutions to this, all of them without luck.
embedding fonts
changing the textfield's antiAliasType
using BitmapData like this:
bmd = new BitmapData (myTextField.width, myTextField.height, true, 0);
bmd.draw (myTextField);
bm = new Bitmap (bmd);
bm.x = myTextField.x;
bm.y = myTextField.y;
bm.cacheAsBitmap = true;
bm.smoothing = true;
this.addChild(bm);`
And then moving the "bm" instance
None of these methods worked.
EDIT: By request, I am adding the relevant code for the actual movement of the text.
stage.addEventListener(Event.ENTER_FRAME, time);
private function time(evt:Event):void
{
bm.x-= textSpeed;
}
The variable textSpeed is defined as a public static var. Its value is 2.
*EDIT2: I've prepared a clean fla-file with nothing but moving text. The same lag occurs for me also here. The code is in the actions panel. Download link
the way Flash IDE works, is that setting the framerate is actually the 'maximum' framerate. That is, it doesn't force the animation to run at that rate - it can vary depending on the machine and available resources.
As far as I know, there's no way to force Flash to run at a certain framerate - the best way to make animations 'smooth' is to use Tween classes like TweenLite.
If you NEED to animate by incrementing position values, then I suggest making it time based instead, for example:
var fps = 24;
var moveTimer:Timer = new Timer(1000/fps);
moveTimer.addEventListener(TimerEvent.TIMER, onMoveTimer);
moveTimer.start();
function onMoveTimer(e:TimerEvent){
bm.x -= 1;
}
Again, this doesn't solve the smoothness of the animation, but it will be much more reliable across different machines than using enter frame.
Try increasing the framerate. Because you naturally try to read text as it animates, you can generally notice the gaps between frames at 24fps. Try setting stage.frameRate to 30, 48, or 60 (60 being the max) and see if that solves your issues. I've had similar issues with animating text in the past and increasing frame rate has fixed them.
I would also recommend only increasing it as needed. You are much more likely to drop frames with a higher frame rate (makes logical sense; each frame has less time to calculate as frame rate increases), so you might want to do something like:
stage.frameRate = 48;
// run animations here
stage.frameRate = 24; // in an Event.COMPLETE handler
That will make sure your animations are smooth while giving the rest of your application the best shot of running well on lesser devices. If you are running a lot of animations, you might consider keeping it elevated permanently.
You should also look into using the Greensock animation library (TweenLite/TweenMax) instead of Flash's built-in tweening. Greensock has a vastly superior API, both in terms of features and performances, especially on mobile.

AS3 - Moving a clip (player) along a path

I'll try to explain my problem in a clear and short way.
I'm writing a grid-game. In this game when the player clicks somewhere, the player moves, along the grid with a path calculated by the computer (because there's obstacles that the player avoid : walls...) to the final point.
It's an isometric grid but it's like it was a basic 2D grid.
So I have my path, which is a Point Array (key points screen coordinates) :
path : [x=10,y=100],[x=40,y=172], .. etc.
To display the movement of the player, I tried to use tweens (TweenLite/TweenMax).
There's no option on TweenLite to wait for a tween to finish before starting the next. In any case the solutions seem complicated (shitty delays/onFinish:function).
The solution I found is acceptable : TweenLite provides a LinePath2D function which works exactly like I wished. The only problem is that it works with only one function (path is the complete array):
var pathanimate:LinePath2D = new LinePath2D(path);
pathanimate.addFollower(Player);
TweenMax.to(pathanimate, 1, { progress:1, ease:Linear.easeNone });
So I can't "touch" anything during the movement. INCLUDING the aspect of the sprite of the player that must changes with the direction during each step of the path (it would be more simple if it LinePath worked with a loop).
I don't know if this is clear (i'm french huh) but I see only but two options :
Keep the LinePath and have, on each frame, some kind of counter/timer that "measures" the direction of the player. Could be heavy in ressources, but keeps the LinePath2D that works very well alone
Find another solution
I'd be glad to hear your ideas and code !
Thanks in advance
Actually I can provide several solutions, but they will include many lines of code. Briefly speaking:
System of waypoints. You have algorithm to set collection of waypoints to your character, and render him (updating from the main gaming loop), and character reaches one waypoint after another by shifting them from the collection.
Working with tweens, append them (so there will be queue).
In both options, you can set new path for the character, all you need is simple logic to approximate current position of the character to the closest grid point, and calculate new path from there, It's very easy with basic grid systems, like:
closestGridCellX = Math.round(this.x / gridCellSize);
closestGridCellY = Math.round(this.y / gridCellSize);