banner



How To Reset Object After Animation In Unity

When making games, you frequently need to breathing on-screen elements to create a narrative or add that special polish to capture the histrion's interest. In the latter case, these furnishings' only purpose is to make the experience enjoyable.

Unity has a powerful and user-friendly blitheness engine that lets you lot animate anything your heart desires. However, some types of animation, peculiarly the most simple ones, don't need the full power of the blitheness engine. You can perform them more efficiently with a more straightforward approach: Tweening techniques.

In this tutorial, you'll acquire almost tweening and how to:

  • Use tweening in GameObjects, such every bit assets and UI.
  • Integrate the LeanTween package in your project.
  • Use rotation, displacement and calibration effects to GameObjects in your projects.
  • Add tweening UI elements to your projects.

Past the time you're done, you'll recall about animations not only in terms of Unity'south Animator but using other types of packages as well. As a bonus, the last sample project will look great!

Final project gameplay, with ball bouncing, colors flashing and crates rotating.

Do yous experience the tween?

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 afterward.

In Assets/RW, you'll find the assets used in this project. Look at the folder structure:

  • Input: Files used past Unity'due south new input organization.
  • Physics Materials: The physics materials used for the ball in the project.
  • Plugins: This folder has LeanTween installed. You'll learn how to install LeanTween in your projects subsequently in the tutorial.
  • Prefabs: The project's prefabs.
  • Scenes: Y'all'll find the sample scene here.
  • Scripts: The C# scripts for this projection.
  • 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 acquire more, make certain to check 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. Employ the correct and left arrows or the A and D buttons on the keyboard to move the paddle. Make the ball bounciness around and break equally many crates equally you wish.

Now, it's time to have a closer expect at tweening.

Why Not Utilise Unity'due south Animator for Everything?

That'south a great question!

Unity already has a module capable of implementing most kinds of animation, so why would you lot want to bring in some other package? Isn't it redundant?

The keyword here is overkill. The animation engine is as well powerful for simpler tasks, and it may drain precious resources from the histrion'south calculator.

Unity'southward Animator Component has a callback part that continuously calls for every Animator on the scene. Animative GameObjects without using the Animator Component is an excellent fashion to keep requirements depression.

What is Tweening?

Simplistically, tweening, or inbetweening, is another name for interpolation. In this operation, a belongings can assume any value between two limits.

For case, imagine a GameObject that translates between two points in a iv second time interval, as shown in the following effigy:

Moving a GameObject between two points.

You know the position at zero seconds and four seconds: As the figure shows, those are the points (0, 0, 0) and (1, 0, 0). However, to breathing it properly, the computer needs to draw each frame.

By getting values between those points, the animation engine can determine that at two seconds, the GameObject should be at (0.5, 0, 0), at ane second, at (0.25, 0, 0), at 3 seconds, (0.75, 0, 0) and so on. This uncomplicated interpolation creates animation using merely unproblematic algebraic operations.

Information technology's possible to brand this blitheness a trivial fancier by using animation curves, also known as tweening curves. In the previous example, to get the position of an element at any given time, you lot had to carve up the total displacement by the elapsed time and add this value to the initial position.

That isn't the but mode to reach the final value: The progression doesn't need to exist uniform. Information technology's time to discuss tweening curves, also chosen easing functions.

In this case, the interpolation is no longer linear just instead uses an arbitrary function to dictate how the element moves. For example, if you lot said the GameObject in the previous example should move similarly to a sine function, the velocity would be lower on the extremes of the function.

For more information on easing functions and their effects, bank check this reference.

Animator Component vs Tweening Techniques

When you're choosing between the two techniques, yous should consider tweening's strengths and limitations.

Tweening is nifty for simple components and animations. A good rule of thumb is to apply tweening whenever y'all desire to breathing something straightforward without sacrificing framerate.

Simply trying to create circuitous animations solely with tweening can speedily get out of hand. The Animator Component's extra bulk and power is ameliorate suited for tackling these more than elaborate animations, such as sprite or skeletal blitheness.

How much overhead is at that place in the Animator Component? Allow's have a moment to compare their functioning.

Performance Comparison

You can employ Unity'south profiler to get a ameliorate view of what's going on backside the scenes in this Animator and tweening comparison. To permit for a better comparing, take an example scene, with sprites moving as shown in the following figure:

A sprite moving sideways.

Now, consider a scene with many of those sprites making the same movement. As their number increases, the computer requirements increase accordingly. For 300 sprites moving sideways with the animator, the Unity profiler shows:

Profiler image showing the animator consuming processing power around the 5ms mark.

The animator is that thick blue line.

That thick blue line is how much processing power Unity'due south Animator component is consuming. Selecting the line at a given point shows what'south happening in Unity's main loop:

The Main Thread in the Profiler window.

Discover that the main villain here is the Animator.Update() method. It'south taking a lot of the main thread processing time. If but there were a way to eliminate it…

That'south where LeanTween enters. LeanTween is a package that provides a lean, lightweight tweening implementation. Without the need to invoke the Animator, the whole process changes dramatically. See what the Unity profiler has to say about it:

Profiler graphic showing how the processing consumption for tweening is lower than for the animator.

The main thread is unlike as well. Have a expect:

The Main Thread in the Profiler window illustrating the performance boost of LeanTween.

And the final blitheness effect is the aforementioned. This demonstration proves that eliminating the Animator Component from simpler animations makes information technology possible to boost performance and enhance your circuitous animations.

Adding LeanTween to Your Projection

To add LeanTween to your projects, go to its Asset Shop page and add to your assets.

When you finish, it'll appear in your package explorer window in Unity. Select it and then click Install. When prompted, click Import to add the package to your projection.

Now, on to using the recently added package in your game.

Animative the Paddle With the Tween Library

The start GameObject yous'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's ever a reaction.

For the histrion to feel the activity, the paddle needs to react to the collision. Yous'll use the translation functions to readapt the paddle accordingly.

Translating Objects with LeanTween

As yous already learned, you can use tweening to displace game elements for a specific amount of fourth dimension. With LeanTween, the move function takes care of full general displacement. You specify the initial position, last position and time that the movement should accept.

However, more specialized functions move the GameObject in a single axis: moveX, moveY and moveZ. In this tutorial, you lot'll utilize the function specialized to movement the paddle along the Y-centrality.

Bouncing the Paddle

You demand to add some displacement to the paddle and make information technology react to the standoff with the ball. Become to Paddle.cs and replace the entire OnCollisionEnter2D() with:

private void OnCollisionEnter2D(Collision2D standoff) {     //one     if (collision.gameObject.tag.Equals("Cog"))     {         //2         LeanTween.cancel(gameObject);         //three         LeanTween.moveY(gameObject, transform.position.y - 0.5f, 0.5f).setEaseShake();     } }        

This code does three primary things:

  1. This line checks if at that place'southward a collision betwixt the paddle and the ball (the "Cog"). In this case, the paddle can't collide with anything else, but it's skilful practice to be clear virtually which collision you lot want to handle.
  2. This function tells LeanTween to end whatever other furnishings that might act on this GameObject. This step helps you lot avoid errors past ensuring no other blitheness effect operates simultaneously on the element.
  3. Finally, this is the line that actually creates motion. If it were a sentence in English language, this office would say, "move the y-axis of the gameObject half a unit downwards, over half a 2d".

At present printing the Play button. You'll see the paddle bounces up and down for one-half a 2d and and then returns to the initial position.

Paddle bouncing when the ball hits it.

Bounciness, paddle, bounce!

Yet, even though the paddle moves along the Y-axis, it goes dorsum to its initial position in the end. This happens considering of the setEaseShake() appended at the stop of LeanTween.moveY(). This ease curve defines that the movement should end at the same indicate where it started, creating the bounciness effect shown on the paddle.

If y'all want, remove setEaseShake() and scout every bit the paddle gets relentlessly pounded to the bottom of the screen. Only call up to add it back in when you're done.

Paddle getting pounded off screen.

Where are y'all going, paddle?

Adding Character to the Brawl

In the starter project, the brawl bounces effectually, breaking the crates and bouncing off the paddle. However, you tin make it a more interesting grapheme.

Currently, the ball animation is based solely on physics: When the ball collides, it reflects and keeps moving. Only, with tweening techniques, y'all can make the ball a lilliputian more interesting.

To create some interesting graphics, begin by changing the calibration of the brawl with tweening effects.

Scaling the brawl

All the examples thus far were nigh movement. However, y'all 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("Histrion"))     {         hitPosition = (ballRigidbody.position.x - collision.rigidbody.position.x)                  / collision.collider.premises.size.ten;              direction = new Vector2(hitPosition, 1).normalized;             ballRigidbody.velocity = direction * BallSpeed;     }     // 1     LeanTween.cancel(gameObject);     transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);     // two     LeanTween.calibration(gameObject, new Vector3(1.0f, 1.0f), 1.0f).setEase(LeanTweenType.punch); }        

Here's a code breakdown:

  1. These two lines reset the GameObject behavior. In addition to LeanTween.cancel(), the ball's scale needs to reset to avoid whatsoever error propagation. If the brawl collides with another element before the animation ends, the beginning scale volition be incorrect, and, in the end, the "normal" size of the ball will exist modified.
  2. Once again, this is the code that actually performs the operation. This time, however, yous're scaling the GameObject instead of moving information technology. 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 dainty the ball behaves now:

The ball bouncing on the paddle.

Personalized Easing Functions

In this example, you used a predefined easing curve for the scale operation. But setEase isn't limited to just LeanTweenType easing curves.

This role also gives you the flexibility of drawing your own curves with Unity's help. Add the following animationCurve variable to the BallScript course:

          public AnimationCurve animationCurve;        

Then, supervene upon:

          LeanTween.scale(gameObject, new Vector3(1.0f, 1.0f), 1.0f).setEase(LeanTweenType.dial);        

With:

          LeanTween.scale(gameObject, new Vector3(1.0f, one.0f), 1.0f).setEase(animationCurve);        

Save the script changes and get to the Hierarchy window. Expand the Thespian Objects GameObject, select the Cog GameObject and look at the Inspector window.

Custom easing function input interface in the Unity Editor.

Here y'all can set up your own easing bend.

You'll see a new parameter that lets you lot draw your easing function graphically. You can likewise select a predefined curve defined past Unity.

Unity interface for selecting or editing the easing curve.

This is particularly helpful for testing considering you can try various curves and behaviors for your scene elements in Play Fashion. You tin fine-tune your game every bit much equally yous want until the game feels exactly as you intend.

For example, if yous set the curve to speedily ascend, similar this:

A curve with a fast ascend rate.

The ball grows quickly in the starting time, and and so plateaus, like and so:

Image of the the ball growing quickly just after colliding.

Nevertheless, if the curve is inverted:

The curve starting smoothly and growing fast.

The ball will begin growing slowly and pick upwards momentum:

Image showing the ball growing slowly in the beginning.

Because you set the ball to reset its scale for every standoff in the code, it'll work with whatever curve you lot choose to elaborate. Even so, to avert relying on setting the size by code, you could try a curve that comes dorsum to the initial size in the end later applying some scaling, similar this:

Curve showing three peaks and returning to the beginning.

Right click the curve and add equally many keys as yous similar to create various effects. This curve gives the ball a rubbery feeling:

Ball with bouncing scale and returning to the original size.

Now create your own rubbery curve and select it every bit the Blitheness Curve for your script.

Color-Changing Effects

In addition to Transform-based effects, similar movement and scaling, y'all can also add color-changing effects.

In BallScript.cs, add together one more line to the cease of OnCollisionEnter2D() to let for color effects:

          gameObject.LeanColor(Color.yellow, 0.5f).setEasePunch();        

This final line makes the ball flash yellowish for half a 2nd, producing the post-obit result:

The ball changes color when it collides with other elements.

Now the ball is a graphic symbol in the game.

In the case of colour changing, you accept the selection of calling the LeanTween role directly on the GameObject, rather than having to pass the GameObject in as an argument, which is a nice bit of syntactic carbohydrate.

Breaking the Blocks

Currently, the blocks interruption, but yous could add together more than interesting behaviors to the blocks afterwards they collide with the ball.

Open Crates.cs. You lot'll run into the code for OnCollisionEnter2D().

In OnCollisionEnter2D(), you find merely a reference to the role that increases the score as the player breaks the crates. But, you'll add more momentarily.

The blocks getting destroyed and simply disappearing.

The blocks just vanish…

Rotating Objects With LeanTween

Past now, you may be wondering which numbers you lot could interpolate next. In this step, you lot'll use 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. At present you'll use LeanTween to add a more than interesting effect to information technology.

Supersede the entire OnCollisionEnter2D() with:

private void OnCollisionEnter2D(Collision2D collision) {     //1     gameObject.GetComponent<Collider2D>().enabled = simulated;     //ii     LeanTween.alpha(gameObject, 0.2f, 0.6f);     //3     LeanTween.rotateAround(gameObject, collision.GetContact(0).normal, 250.0f, 0.6f).setDestroyOnComplete(truthful);     // Increases the score      GameManager.Instance.IncreaseScore(i); }        

Here'due south what the code does:

  1. Initially, you disable the GameObject's collider to avoid getting additional collisions betwixt when crate is hit and when it finally disappears from the scene.
  2. To give the illusion of the crate disappearing, you use the alpha channel to decrease the element's opacity to 0.2 over 0.six seconds.
  3. rotateAround() rotates the gameObject around the bespeak where the standoff happened, 250 degrees along 0.half dozen seconds. This creates a more responsive feel as the crate rotates around the point of contact between itself and the ball. Then, the lawmaking tells LeanTween to destroy the GameObject afterwards the blitheness finishes, removing the elements from the scene just after the marked operations finishes.

Now press Play and see how cool your work looks.

Blocks rotating before getting destroyed.

Much amend now!

Tweening UI Elements

Yous've come up a long way in calculation animation to the project. Even though the individual animations are unproblematic, when everything comes together, the composition is crawly.

But if you lot look closely, y'all'll discover that non everything has dynamic behavior.

The score text is withal static. It counts the points correctly, but there isn't much to it.

In Unity, UI elements are as well GameObjects, then it should be elementary to add together some furnishings, right? Right!

The score increasing just changing the text.

How information technology is at present.

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 entire IncreaseScore(int value) with:

public void IncreaseScore(int value) {     gameScore += value;     scoreDisplay.text = gameScore.ToString();      // 1     LeanTween.cancel(scoreDisplay.gameObject);     scoreDisplay.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);     scoreDisplay.transform.localScale = Vector3.one;      // 2     LeanTween.rotateZ(scoreDisplay.gameObject, 15.0f, 0.5f).setEasePunch();     LeanTween.scaleX(scoreDisplay.gameObject, i.5f, 0.5f).setEasePunch(); }        

Equally this lawmaking has a few new functions, analyze it past blocks:

  1. This block resets the score display GameObject's appearance. These lines terminate any tweening performance acting on scoreDisplay and reset its rotation and scale to avert any error propagation during gameplay.
  2. The functions in this block add rotation and calibration effects to the scoreDisplay GameObject. Here, y'all declare a rotation along the Z-axis and a scale along the X-axis, with the same easing function.

Equally y'all may take realized, yous can perform the same operations available for every other GameObject on the UI elements. Nonetheless, while the tweening code was encapsulated inside each 1, the tweening lawmaking for the score is inside the GameManager class.

Now, run the game and see your newly animated scores add together upward.

The score increase animation.

Much better now!

You tin can employ LeanTween to animate other elements, non but ones where y'all include the script files.

Tweening the Background Color

If yous press Play at present, yous'll see that the game is complete, but there's still room for improvement. The background could respond 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 Hierarchy window. Then select the Background GameObject and look at its backdrop in the Inspector Window.

Discover that the Sprite Renderer component has a colour other than white. This helps create the illusion of 3-dimensional infinite, with the groundwork being at a distance from the foreground.

To human action on information technology, you'll need a reference to the Background GameObject. So, at the top of GameManager.cs, right below:

public GameObject Paddle;        

Add together two more variables to stand for the reference to the Background GameObject and how much information technology should milkshake, like this:

public GameObject Background; public float backgroundShakeRate = two.0f;        

At present, supersede IncreaseScore(int value) again with the following:

public void IncreaseScore(int value) {     gameScore += value;     scoreDisplay.text = gameScore.ToString();      LeanTween.cancel(scoreDisplay.gameObject);     scoreDisplay.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);     scoreDisplay.transform.localScale = Vector3.one;      LeanTween.rotateZ(scoreDisplay.gameObject, 15.0f, 0.5f).setEasePunch();     LeanTween.scaleX(scoreDisplay.gameObject, 1.5f, 0.5f).setEasePunch();      // 1     LeanTween.motion(Background.gameObject, Random.insideUnitCircle * backgroundShakeRate, 0.5f).setEasePunch();      // ii     Background.LeanColor(Colour.reddish, 0.3f).setEasePunch().setOnComplete(() =>         {             Groundwork.GetComponent<SpriteRenderer>().color = new Colour(0.38f, 0.38f, 0.38f);         }); }        

Both motion and LeanColor were already used for other elements. At present, you'll use them slightly differently:

  1. This code uses LeanTween.motion(). But in this example, the motion is performed in a random management by using Random.insideUnitCircle to return a random Vector2 inside a unit circle (a circle with a radius of 1).
  2. This code shows how to define a lambda expression to execute as soon as the animation finishes. In this example, the lawmaking redefines the Groundwork sprite color aspect to the default value to avoid irresolute the color, merely like the brawl size resets every blitheness round.

Don't forget to add the reference you created in the script in the editor as well! Drag the Background GameObject from the Hierarchy window to the appropriate slot in the GameManager.

Adding a reference

Now, click Play and enjoy playing your game. Look how much better information technology looks compared to the initial project:

The initial project without any animation effects.

The starter project. Feels like information technology was twenty minutes ago…

Final project gameplay, with ball bouncing, colors flashing and crates rotating.

The final projection, it just looks much ameliorate.

Where to Go From Here

From here, y'all can tween abroad anything!

You can download the completed projection files by clicking the Download Materials button at the top or the bottom of this tutorial and continue exploring.

Why not get a feel for creating your custom ease curves in the Unity Editor? Try replacing some easing functions for the elements in the project and modify them as much as you like.

You can as well scan the official LeanTween documentation for boosted details on the API.

I promise y'all enjoyed this tutorial. If you lot take questions, comments or desire to show your final project, please bring together the forums below!

Source: https://www.raywenderlich.com/27209746-tweening-animations-in-unity-with-leantween

Posted by: arneybadeltudy.blogspot.com

0 Response to "How To Reset Object After Animation In Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel