I wan't to implement a frictionless spring in unity3D to animate a gameobject as if it where floating by moving up and down. I am doing it with an animation but if I use forces they can combine an create richer sequences.
I could do:
//Update
rigidbody.addforce( springForce );
The force is just the change in the velocity so I could also do
//Update
rigidbody.velocity += Time.deltaTime * springForce / rigidbody.mass;
The question remains, is adding a force each frame efficient? Should I skip some frames or just do the animation to avoid performance issues? Note: I program for mobile.
The difference between Update and FixedUpdate is this:
Update is always called as quickly as possible. The time between calls is tracked in deltaTime. Even if "as quickly as possible" turns out to be really slow, only a single call to Update is made with a high DeltaTime value.
FixedUpdate is never called more often than the physics framerate. If things slow down and the time for several physics frames passes without the necessary calls being made, Unity will try to catch up by calling FixedUpdate multiple times. For example, if the physics framerate is 0.02 and slow code holds up the game for 0.06 seconds, Unity will call FixedUpdate 3 times to try and catch up.
You can probably see the problem at this stage: physics movement tends to be complicated with acceleration, deceleration, collisions etc. If you add forces in Update then the amount of force added and the exact timing with which it is added will vary based on the speed the game is running at. Also, if the game slows down, the physics engine will be doing multiple updates per physics frame to catch up (it works in the same way FixedUpdate does) and your Update method would be unable to compensate for this (actually, it is possible, but only if you basically duplicate the catch-up code Unity already has which is pointless)
To use your spring example, assuming you had all the spring behaviour correct but in Update instead of FixedUpdate, if the game was running fast then Update could be called several times with the object not moving - not because the spring force has failed to move it but because the physics engine has not yet run to actually pay attention to the force and make the object move. If the game was running slow then the object could hit the spring and then the effect of the forces on the object would be calculated multiple times before the spring was calculated again. This could cause the object to move a tiny bit out of contact with the spring and end up bouncing, or to actually interpenetrate the spring and force restitution to occur.
If an object is just moving in a straight line with no physics then its position over time is defined by very simple equations which can be evaluated at any value, so you can use Update.
Unlike the previous answer there is actually a good reason to use deltaTime in a FixedUpdate method - Unity automatically sets it equal to fixedDeltaTime in this case, so your code can adapt if you change the physics framerate.
First you would do physics updates in die FixedUpdate method. So the force wouldn't be applied every frame but every physics tick (default 0.02 seconds I think).
If you should do that heavily depends on your needs. If you want a realistic simulation of a floating object you probably need to apply the force every physics tick. Wether you should use a spring for that is another question. There are some floating scripts in the unify wiki:
http://wiki.unity3d.com/index.php?title=Main_Page
Or you could have a look at this very interesting script:
http://forum.unity3d.com/threads/72974-Buoyancy-script
When adding a force in Unity through the use of AddForce you have the choice of a couple of ForceModes (http://docs.unity3d.com/Documentation/ScriptReference/ForceMode.html). So it might be a little different to your change of velocity depending on the mode you will use.
Another point: When using FixedUpdate you won't need to use Time.deltaTime as the ticks always have the same time-lag.
If you decide to apply the force less often you can change the time between physics ticks to increase performance:
http://docs.unity3d.com/Documentation/ScriptReference/Time-fixedDeltaTime.html
http://docs.unity3d.com/Documentation/ScriptReference/Time-timeScale.html
Related
I want create a simple 2D game in Unity3D, in which one of the entities has to grow and shrink. This is done by merging simple shapes.
A rough example in the picture below just to show what I mean:
It grows by adding components and shrinks by removing them. There will be a lot of entities on the screen so the performance is very important.
Is it possible to change dynamically the shape of one gameobject? If not, which of the following solutions is more suitable and why?
Constantly add new gameobjects (shapes) to the previous one and then remove them?
Create an animation. In this case is it possible to change the animation speed at runtime so for example first it grows faster and then grows slower or shrinks? My issue is whether the change of speed will apply to the whole loop of the animation or is it possible to apply it in the middle (so that the speed of shrinking and growing is different)? I would prefer the latter to happen.
If you have any other suggestions I'd be glad to hear them.
Create an empty game object and add all of these small pieces as its child. Then you can disable/enable whichever you want with gameObject.SetActive(false/true);
Depends what is "lots of objects" and what is the target platform.
You can easily have hundreds of sprites on screen in any case, especially if they get batched : http://docs.unity3d.com/Manual/DrawCallBatching.html
And there is big performance benefit to use object pooling,
instead of instancing new objects and destroying old ones.
Having hundreds of animated objects would cause slowdown,
Mecanim Animator seems to be slower than the original Animation component.
Other options:
- Create custom mesh that you modify at runtime (by adding/removeing vertices to it), this also allows to freely modify the shapes (by moving the vertices) : http://docs.unity3d.com/ScriptReference/Mesh.html
I'm trying to make the stage.show() slow down. I figured out I might need to set KeyFrame, but am stuck at KeyValue, not understanding T endValue or Interpolator interpolator. Is this the right approach? If so could anyone explain to me what type is T.
Thank you!
You can't slow stage.show() down, if stage is a JavaFX Stage, because this is not an animation.
Controlling Animation Speed
An animation's speed is primarily controlled by its rate. Varying either the rate of playback of the animation or the duration of the animation will probably be all you need to do to get the animation speed you want.
animation.setRate(2) // play the animation at double speed.
animation.setRate(0.5) // play the animation at half speed.
On Interpolation
An interpolator is a mathematical function for calculating intermediate values between points. Here is an article on interpolation.
In JavaFX, the interpolators are used to define easing functions for changing values between keyframes of an animation. Likely, for what you are doing, either a straight linear interpolator or an ease in + ease out interpolator will be fine (those are the two most commonly used interpolators). Most of the time, the default interpolator used by JavaFX suffices and you don't have to change it.
The apparent speed of an animation might also be effected by the interpolated easing function applied to the animation's key values or by the magnitude of a keyvalue change (e.g. number of pixels translated, number of times to scale) divided by the keyframe's duration.
Further reference
If you don't understand what this means, then read the JavaFX animation documentation which will define the terms referenced and provide examples on how to use them.
Additional items in your question
What you want to do ("stage.show() slow down") is ambiguous to me in the context of animations, so I couldn't advise an approach for that - as TheJeed correctly states stage.show() is not an animation, so it makes no sense to try to apply animation to a stage.show() call.
T in the context of a KeyValue is a generic type, which seems to answer the question in your question but not the question in your title.
I agree the question was poorly asked. I didn't have the right approach. Just simply changing thread.sleep() will do the work.
But thank you guys anyway!
I'm making a snake game and on every tick the snake moves. because the snake is moving a whole unit on each tick the animation is jumpy. The game is on an invisable grid so the snake can only change directions at specific points.
Would it be considered better practice to have a timer that will move the snake a pixels at a time counting it with a variable, and on every n tick run the code to change direction. Or is it better to have two separate timers; one for move the snake a pixel at a time and another for changing the snakes direction?
Essentially, you're creating a "game-loop" to update the displayList (in Actionscript) and re-draw your view. When the game gets complex, Timers and listening for ENTER_FRAME events will be constrained to the flashplayer settings for screen refresh (i.e. it's FPS) and the CPU's rendering based on what it is tasked to process.
For frame-rate independent animation, you should probably use a combination of ENTER_FRAME to track milliseconds and GetTimer() calls to more accurately (to the millisecond) call animations and normalize the experience across a variety of platforms.
Basically, listen for the ENTER_FRAME event, check the current milliseconds since the last update and if it exceeds your refresh-rate (in terms of milli's), fire off the animation/state update: check for snake collision detection with a "direction-block" - handle if true, then update the snake's movement / position / state.
Flash updates the Display List at whatever it's settings, and CPU / machine-dependent issues are. The key, I've found, is to make sure you're normalizing the speed of updates to make the experience consistent. Timer's have their usage, but can cause memory performance issues. ENTER_FRAME is synced to the main timeline / frame-rate settings.
For a dated, but interesting discussion 3 years ago, check out this post from actionscript.org.
I have a particle system using basic spritebatch, where the particles are being created and destroyed based on decremental alpha value till 0.
The perfomance of the system is quite poor on pc, and very poor on xbox, with about a hundred particles on screen before significant fps slow down, I've read around regarding how to improve performance but does anyone have any tips on how to implment them, for exmaple what is the best way to - reuse particles rather than kill()? Does the image size of each particle make a difference? if I don't rotate each particle will this help?
I've played around with each of these suggestions but don't receive any significant improvement - does anyone have any advice - is it worth going gpu rather than cpu based?
From what I recall destroying and creating particles slows down the performance substantially.
You might want to reuse particles.
Not sure about image size or rotation drastically reducing performance as long as the image isn't substantially large.
I would have an array with swapping dead particles to the end of the active particles therefore processing only active particles.
For example:
Make an array of MAX particles;
When you need a particle grab particle_array[count];
Increment count.
When a particle dies, decrement count, swap the particle with particle_array[count];
Update only count particles;
Hope this helps.
I entirely agree with subsonic's answer, but I wanted to expand on it.
Creating a new particle every time and destroying (or letting go of) old particles creates a LOT of garbage. The garbage avoidance mantra in C#, particularly on Xbox (due to the compact framework's poor garbage handling), is to NEVER new a class type in your update/draw loop. ALWAYS pre-create into pools. Shawn H explains: http://blogs.msdn.com/b/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx.
One other thing to consider is that you using multiple textures can cause slowdown for sprite batch due to multiple draw calls. Try to merge multiple particle textures into one and use the source rectangle SpriteBatch.Draw parameter.
Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?
You're talking about two different things here.
One is momentum - giving things residual motion when you release them from a drag. This is simply about remembering the velocity of a thing when the user releases it, then applying that velocity to the object every frame and also reducing the velocity every frame by some amount. How you reduce velocity every frame is what you experiment with to get the feel right.
The other thing is ease-in and ease-out animation. This is about smoothly accelerating/decelerating objects when you move them between two positions, instead of just linearly interpolating. You do this by simply feeding your 'time' value through a sigmoid function before you use it to interpolate an object between two positions. One such function is
smoothstep(t) = 3*t*t - 2*t*t*t [0 <= t <= 1]
This gives you both ease-in and ease-out behaviour. However, you'll more commonly see only ease-out used in GUIs. That is, objects start moving snappily, then slow to a halt at their final position. To achieve that you just use the right half of the curve, ie.
smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1
Mike F's got it: you apply a time-position function to calculate the position of an object with respect to time (don't muck around with velocity; it's only useful when you're trying to figure out what algorithm you want to use.)
Robert Penner's easing equations and demo are superb; like the jQuery demo, they demonstrate visually what the easing looks like, but they also give you a position time graph to give you an idea of the equation behind it.
What you are looking for is interpolation. Roughly speaking, there are functions that vary from 0 to 1 and when scaled and translated create nice looking movement. This is quite often used in Flash and there are tons of examples: (NOTE: in Flash interpolation has picked up the name "tweening" and the most popular type of interpolation is known as "easing".)
Have a look at this to get an intuitive feel for the movement types:
SparkTable: Visualize Easing Equations.
When applied to movement, scaling, rotation an other animations these equations can give a sense of momentum, or friction, or bouncing or elasticity. For an example when applied to animation have a look at Robert Penners easing demo. He is the author of the most popular series of animation functions (I believe Adobe's built in ones are based on his). This type of transition works equally as well on alpha's (for fade in).
There is a bit of method to the usage. easeInOut start slow, speeds up and the slows down. easeOut starts fast and slows down (like friction) and easeIn starts slow and speeds up (like momentum). Depending on the feel you want you choose the appropriate one. Then you choose between Sine, Expo, Quad and so on for the strength of the effect. The others are easy to work out by their names (e.g. Bounce bounces, Back goes a little further then comes back like an elastic).
Here is a link to the equations from the popular Tweener library for AS3. You should be able to rewrite these in JavaScript (or any other language) with little to no trouble.
It's playing with the numbers.. What feels good is good.
I've tried to develop magic formulas myself for years. In the end the ugly hack always felt best. Just make sure you somehow time your animations properly and don't rely on some kind of redraw/refresh rate. These tend to change based on the OS.
Im no expert on this either, but I beleive they are done with quadratic formulas, that, when given the correct parameters, start fast or slow and dramatically increase or decrease towards the end until a certain point is reached.