How To Get An Animation Length That Is Not Currently Playing Unity
When making games, you frequently need to animate on-screen elements to create a narrative or add that special polish to capture the player's involvement. In the latter example, these furnishings' only purpose is to brand the experience enjoyable.
Unity has a powerful and user-friendly animation engine that lets you animate anything your heart desires. Still, some types of blitheness, peculiarly the near simple ones, don't need the full power of the animation engine. Yous can perform them more efficiently with a more than straightforward arroyo: Tweening techniques.
In this tutorial, you lot'll acquire about tweening and how to:
- Utilize tweening in GameObjects, such as assets and UI.
- Integrate the LeanTween packet in your project.
- Utilise rotation, displacement and scale effects to GameObjects in your projects.
- Add tweening UI elements to your projects.
By the time you're done, you'll think about animations not merely in terms of Unity's Animator but using other types of packages also. As a bonus, the final sample project will look groovy!
Getting Started
Click the Download Materials button at the top or bottom of the tutorial to download the starter project. This project requires Unity 2020.3.20f1 or later.
In Assets/RW, you'll find the avails used in this projection. Look at the folder structure:
- Input: Files used by Unity's new input system.
- Physics Materials: The physics materials used for the brawl in the project.
- Plugins: This folder has LeanTween installed. You lot'll learn how to install LeanTween in your projects later in the tutorial.
- Prefabs: The project's prefabs.
- Scenes: Y'all'll detect the sample scene here.
- Scripts: The C# scripts for this project.
- Sprites: The game art, courtesy of the kenney.nl industrial platformer pack.
- Text Mesh Pro: Files used by Text Mesh Pro where you create the UI. To learn more, make sure to cheque out the TextMesh Pro tutorial.
Whew, that was a lot of folders!
Open the TweenBreaker scene in Assets/RW/Scenes, then click Play to try this Breakout clone. Utilise the right and left arrows or the A and D buttons on the keyboard to move the paddle. Make the ball bounciness around and pause as many crates every bit yous wish.
Now, it'southward time to take a closer look at tweening.
Why Not Use Unity's Animator for Everything?
That's a great question!
Unity already has a module capable of implementing most kinds of blitheness, so why would you desire to bring in another package? Isn't information technology redundant?
The keyword here is overkill. The blitheness engine is also powerful for simpler tasks, and it may bleed precious resources from the thespian'due south reckoner.
Unity's Animator Component has a callback part that continuously calls for every Animator on the scene. Animating GameObjects without using the Animator Component is an first-class fashion to proceed requirements low.
What is Tweening?
Simplistically, tweening, or inbetweening, is some other name for interpolation. In this operation, a belongings can assume any value between two limits.
For example, imagine a GameObject that translates between 2 points in a four 2nd time interval, as shown in the post-obit figure:
You know the position at zero seconds and iv seconds: As the figure shows, those are the points (0, 0, 0) and (one, 0, 0). Notwithstanding, to breathing it properly, the computer needs to draw each frame.
By getting values between those points, the animation engine can decide that at two seconds, the GameObject should be at (0.5, 0, 0), at one second, at (0.25, 0, 0), at 3 seconds, (0.75, 0, 0) and so on. This simple interpolation creates animation using simply simple algebraic operations.
Information technology's possible to brand this animation a little fancier by using blitheness curves, as well known every bit tweening curves. In the previous case, to go the position of an chemical element at any given time, you had to divide the total displacement by the elapsed time and add together this value to the initial position.
That isn't the only mode to accomplish the final value: The progression doesn't need to exist compatible. It's time to discuss tweening curves, also chosen easing functions.
In this instance, the interpolation is no longer linear but instead uses an arbitrary part to dictate how the element moves. For example, if you said the GameObject in the previous example should movement similarly to a sine part, the velocity would be lower on the extremes of the office.
For more information on easing functions and their effects, check this reference.
Animator Component vs Tweening Techniques
When you're choosing between the 2 techniques, you should consider tweening's strengths and limitations.
Tweening is dandy for simple components and animations. A good dominion of thumb is to utilise tweening whenever y'all desire to animate something straightforward without sacrificing framerate.
Simply trying to create complex animations solely with tweening can rapidly get out of hand. The Animator Component's extra bulk and ability is better suited for tackling these more elaborate animations, such as sprite or skeletal animation.
How much overhead is there in the Animator Component? Let's take a moment to compare their operation.
Functioning Comparison
Yous can use Unity'due south profiler to become a better view of what'due south going on behind the scenes in this Animator and tweening comparing. To allow for a better comparing, take an instance scene, with sprites moving equally shown in the following figure:
At present, consider a scene with many of those sprites making the same movement. As their number increases, the estimator requirements increase appropriately. For 300 sprites moving sideways with the animator, the Unity profiler shows:
That thick blue line is how much processing power Unity's Animator component is consuming. Selecting the line at a given point shows what'due south happening in Unity's main loop:
Notice that the master villain here is the Animator.Update()
method. It's taking a lot of the main thread processing time. If only in that location were a way to eliminate it…
That'south where LeanTween enters. LeanTween is a parcel that provides a lean, lightweight tweening implementation. Without the need to invoke the Animator, the whole process changes dramatically. Run into what the Unity profiler has to say about it:
The main thread is different too. Accept a look:
And the terminal blitheness effect is the aforementioned. This demonstration proves that eliminating the Animator Component from simpler animations makes it possible to boost performance and enhance your circuitous animations.
Adding LeanTween to Your Project
To add together LeanTween to your projects, go to its Asset Shop folio and add to your assets.
When you finish, it'll appear in your parcel explorer window in Unity. Select it and and so click Install. When prompted, click Import to add the packet to your projection.
Now, on to using the recently added package in your game.
Animating the Paddle With the Tween Library
The first GameObject you'll animate is the paddle. Initially, the paddle doesn't react to the ball collisions, which doesn't seem realistic. After all, when things hit each other in real life, there'due south e'er a reaction.
For the role player to feel the activity, the paddle needs to react to the collision. You'll use the translation functions to displace the paddle accordingly.
Translating Objects with LeanTween
As you already learned, y'all tin can utilise tweening to displace game elements for a specific corporeality of time. With LeanTween, the move function takes care of general deportation. You lot specify the initial position, final position and fourth dimension that the movement should take.
However, more specialized functions motion the GameObject in a single centrality: moveX
, moveY
and moveZ
. In this tutorial, you'll use the office specialized to move the paddle along the Y-axis.
Bouncing the Paddle
Yous need to add some deportation to the paddle and go far react to the standoff with the ball. Go to Paddle.cs and supercede the entire OnCollisionEnter2D()
with:
private void OnCollisionEnter2D(Collision2D collision) { //1 if (standoff.gameObject.tag.Equals("Cog")) { //2 LeanTween.cancel(gameObject); //iii LeanTween.moveY(gameObject, transform.position.y - 0.5f, 0.5f).setEaseShake(); } }
This code does three main things:
- This line checks if there'south a collision between the paddle and the brawl (the "Cog"). In this example, the paddle can't collide with anything else, but information technology's proficient practise to be clear about which collision you want to handle.
- This function tells LeanTween to finish any other effects that might act on this GameObject. This step helps yous avert errors by ensuring no other animation effect operates simultaneously on the element.
- Finally, this is the line that really creates movement. If it were a sentence in English, this function would say, "move the y-axis of the gameObject half a unit downwardly, over half a second".
Now press the Play push button. Yous'll see the paddle bounces up and downwards for one-half a 2nd and then returns to the initial position.
Even so, even though the paddle moves forth the Y-centrality, it goes back to its initial position in the end. This happens because of the setEaseShake()
appended at the end of LeanTween.moveY()
. This ease curve defines that the movement should end at the same point where it started, creating the bounce effect shown on the paddle.
If you want, remove setEaseShake()
and watch every bit the paddle gets relentlessly pounded to the bottom of the screen. But remember to add it back in when you're washed.
Adding Character to the Ball
In the starter project, the brawl bounces around, breaking the crates and bouncing off the paddle. However, y'all tin make it a more interesting character.
Currently, the ball animation is based solely on physics: When the ball collides, information technology reflects and keeps moving. Merely, with tweening techniques, you can make the ball a picayune more interesting.
To create some interesting graphics, begin by changing the calibration of the ball with tweening furnishings.
Scaling the ball
All the examples thus far were well-nigh movement. However, you can choose a value for any given property.
To illustrate that concept, replace OnCollisionEnter2D()
in BallScript.cs with:
private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag.Equals("Player")) { hitPosition = (ballRigidbody.position.x - collision.rigidbody.position.x) / collision.collider.premises.size.ten; direction = new Vector2(hitPosition, one).normalized; ballRigidbody.velocity = direction * BallSpeed; } // 1 LeanTween.cancel(gameObject); transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); // 2 LeanTween.scale(gameObject, new Vector3(1.0f, ane.0f), ane.0f).setEase(LeanTweenType.punch); }
Here's a code breakup:
- These two lines reset the GameObject beliefs. In addition to
LeanTween.cancel()
, the ball's scale needs to reset to avoid any error propagation. If the brawl collides with another element before the animation ends, the beginning scale will exist incorrect, and, in the stop, the "normal" size of the brawl will be modified. - Again, this is the code that actually performs the operation. This fourth dimension, even so, you're scaling the GameObject instead of moving it. This scales the ball from its normal size (0.4) to i.0 and back, thanks to the
punch
easing function.
Press the Play button. Expect at how nice the ball behaves now:
Personalized Easing Functions
In this example, you used a predefined easing curve for the scale functioning. But setEase
isn't limited to only LeanTweenType
easing curves.
This function too gives you lot the flexibility of cartoon your ain curves with Unity's aid. Add together the following animationCurve
variable to the BallScript
class:
public AnimationCurve animationCurve;
Then, supervene upon:
LeanTween.scale(gameObject, new Vector3(1.0f, i.0f), 1.0f).setEase(LeanTweenType.punch);
With:
LeanTween.calibration(gameObject, new Vector3(one.0f, ane.0f), 1.0f).setEase(animationCurve);
Salve the script changes and go to the Hierarchy window. Expand the Thespian Objects GameObject, select the Cog GameObject and await at the Inspector window.
You lot'll see a new parameter that lets you draw your easing function graphically. You tin also select a predefined bend defined by Unity.
This is particularly helpful for testing because you tin can try various curves and behaviors for your scene elements in Play Mode. You lot can fine-tune your game every bit much as you want until the game feels exactly every bit yous intend.
For instance, if yous ready the curve to quickly ascend, like this:
The ball grows chop-chop in the beginning, and then plateaus, like so:
However, if the curve is inverted:
The ball volition brainstorm growing slowly and pick upwards momentum:
Considering you lot ready the ball to reset its scale for every standoff in the code, information technology'll work with any curve yous cull to elaborate. However, to avert relying on setting the size past code, you could try a curve that comes back to the initial size in the stop later on applying some scaling, like this:
Right click the bend and add as many keys as you like to create various effects. This curve gives the ball a rubbery feeling:
At present create your own rubbery curve and select it as the Blitheness Bend for your script.
Colour-Changing Effects
In improver to Transform-based effects, similar motion and scaling, y'all tin can too add color-changing effects.
In BallScript.cs, add one more line to the cease of OnCollisionEnter2D()
to allow for color effects:
gameObject.LeanColor(Color.xanthous, 0.5f).setEasePunch();
This final line makes the brawl flash yellow for half a second, producing the following effect:
In the case of colour changing, you have the pick of calling the LeanTween function directly on the GameObject, rather than having to pass the GameObject in as an argument, which is a nice bit of syntactic sugar.
Breaking the Blocks
Currently, the blocks suspension, but you could add together more than interesting behaviors to the blocks later they collide with the ball.
Open up Crates.cs. You lot'll see the lawmaking for OnCollisionEnter2D()
.
In OnCollisionEnter2D()
, you lot find simply a reference to the role that increases the score every bit the player breaks the crates. But, you'll add together more momentarily.
Rotating Objects With LeanTween
By now, you lot may exist wondering which numbers you could interpolate side by side. In this step, you'll employ tweening on rotations to create a destroy animation for the crates.
In the original code, when the ball collides with the crates, it simply disappears. Now you'll use LeanTween to add a more interesting effect to information technology.
Supersede the unabridged OnCollisionEnter2D()
with:
individual void OnCollisionEnter2D(Collision2D collision) { //1 gameObject.GetComponent<Collider2D>().enabled = fake; //two LeanTween.alpha(gameObject, 0.2f, 0.6f); //3 LeanTween.rotateAround(gameObject, standoff.GetContact(0).normal, 250.0f, 0.6f).setDestroyOnComplete(true); // Increases the score GameManager.Instance.IncreaseScore(1); }
Here's what the code does:
- Initially, you disable the GameObject'southward collider to avoid getting boosted collisions betwixt when crate is hitting and when it finally disappears from the scene.
- To give the illusion of the crate disappearing, you use the alpha channel to decrease the chemical element's opacity to 0.2 over 0.6 seconds.
-
rotateAround()
rotates the gameObject around the indicate where the collision happened, 250 degrees forth 0.6 seconds. This creates a more responsive feel as the crate rotates around the point of contact between itself and the ball. Then, the code tells LeanTween to destroy the GameObject after the animation finishes, removing the elements from the scene just subsequently the marked operations finishes.
Now printing Play and see how cool your work looks.
Tweening UI Elements
Yous've come a long way in calculation blitheness to the project. Even though the individual animations are unproblematic, when everything comes together, the composition is crawly.
Merely if you look closely, y'all'll notice that not everything has dynamic beliefs.
The score text is still static. It counts the points correctly, just there isn't much to it.
In Unity, UI elements are also GameObjects, and so it should be unproblematic to add together some effects, right? Right!
Score Increment Animation
The GameManager has a reference to the text object and is responsible updating the score.
In GameManager.cs, find and replace the unabridged IncreaseScore(int value)
with:
public void IncreaseScore(int value) { gameScore += value; scoreDisplay.text = gameScore.ToString(); // 1 LeanTween.abolish(scoreDisplay.gameObject); scoreDisplay.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f); scoreDisplay.transform.localScale = Vector3.one; // ii LeanTween.rotateZ(scoreDisplay.gameObject, xv.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, 1.5f, 0.5f).setEasePunch(); }
As this code has a few new functions, analyze it past blocks:
- This block resets the score display GameObject'south appearance. These lines finish whatsoever tweening operation acting on
scoreDisplay
and reset its rotation and scale to avert any error propagation during gameplay. - The functions in this block add together rotation and calibration effects to the
scoreDisplay
GameObject. Here, yous declare a rotation along the Z-axis and a scale along the 10-axis, with the same easing office.
As you may have realized, you can perform the same operations available for every other GameObject on the UI elements. However, while the tweening code was encapsulated within each one, the tweening lawmaking for the score is inside the GameManager
grade.
Now, run the game and run across your newly animated scores add up.
You lot can use LeanTween to animate other elements, not just ones where you include the script files.
Tweening the Background Color
If yous press Play at present, you'll see that the game is complete, but there's still room for improvement. The background could answer to the game actions as well. Information technology's the perfect opportunity to go the extra mile and add a few more than interesting effects to the visuals.
Before jumping into the code, expand the Level Geometry GameObject in the Bureaucracy window. So select the Background GameObject and look at its backdrop in the Inspector Window.
Find that the Sprite Renderer component has a color other than white. This helps create the illusion of iii-dimensional infinite, with the background beingness at a distance from the foreground.
To act on information technology, you lot'll need a reference to the Background GameObject. So, at the top of GameManager.cs, correct beneath:
public GameObject Paddle;
Add together two more variables to stand for the reference to the Background GameObject and how much it should shake, like this:
public GameObject Background; public float backgroundShakeRate = 2.0f;
At present, replace IncreaseScore(int value)
over again with the post-obit:
public void IncreaseScore(int value) { gameScore += value; scoreDisplay.text = gameScore.ToString(); LeanTween.abolish(scoreDisplay.gameObject); scoreDisplay.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f); scoreDisplay.transform.localScale = Vector3.ane; LeanTween.rotateZ(scoreDisplay.gameObject, xv.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, 1.5f, 0.5f).setEasePunch(); // ane LeanTween.motion(Background.gameObject, Random.insideUnitCircle * backgroundShakeRate, 0.5f).setEasePunch(); // 2 Background.LeanColor(Color.red, 0.3f).setEasePunch().setOnComplete(() => { Background.GetComponent<SpriteRenderer>().colour = new Color(0.38f, 0.38f, 0.38f); }); }
Both move
and LeanColor
were already used for other elements. At present, you'll use them slightly differently:
- This code uses
LeanTween.motility()
. But in this case, the motility is performed in a random direction past usingRandom.insideUnitCircle
to render a randomVector2
within a unit circumvolve (a circle with a radius of 1). - This lawmaking shows how to define a lambda expression to execute as before long as the animation finishes. In this case, the code redefines the Background sprite color attribute to the default value to avoid changing the color, but like the ball size resets every animation round.
Don't forget to add the reference you created in the script in the editor as well! Drag the Groundwork GameObject from the Hierarchy window to the appropriate slot in the GameManager.
Now, click Play and enjoy playing your game. Look how much better it looks compared to the initial projection:
Where to Go From Here
From here, you can tween away anything!
You can download the completed project files by clicking the Download Materials button at the elevation or the bottom of this tutorial and proceed exploring.
Why not get a experience for creating your custom ease curves in the Unity Editor? Endeavor replacing some easing functions for the elements in the projection and modify them as much as you like.
Y'all can also browse the official LeanTween documentation for boosted details on the API.
I promise you enjoyed this tutorial. If you lot have questions, comments or want to show your terminal project, please join the forums beneath!
Source: https://www.raywenderlich.com/27209746-tweening-animations-in-unity-with-leantween
Posted by: sanchezhoullatc.blogspot.com
0 Response to "How To Get An Animation Length That Is Not Currently Playing Unity"
Post a Comment