How Tu Put Animation With The Same Size Unitu
When making games, you lot frequently demand to animate on-screen elements to create a narrative or add that special polish to capture the player's interest. In the latter example, these effects' simply purpose is to make the experience enjoyable.
Unity has a powerful and user-friendly blitheness engine that lets you animate anything your heart desires. Even so, some types of animation, peculiarly the nigh simple ones, don't need the full power of the animation engine. You can perform them more than efficiently with a more straightforward approach: Tweening techniques.
In this tutorial, you'll learn near tweening and how to:
- Utilize tweening in GameObjects, such every bit assets and UI.
- Integrate the LeanTween package in your project.
- Apply rotation, displacement and scale effects to GameObjects in your projects.
- Add tweening UI elements to your projects.
By the time you lot're washed, you'll think nigh animations not only in terms of Unity'south Animator but using other types of packages as well. Every bit a bonus, the concluding sample project will look not bad!
Do y'all feel the tween?
Getting Started
Click the Download Materials push button at the top or bottom of the tutorial to download the starter projection. This projection requires Unity 2020.three.20f1 or later on.
In Assets/RW, you'll detect the avails used in this project. Look at the folder structure:
- Input: Files used by Unity'south new input system.
- 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 later in the tutorial.
- Prefabs: The project'south prefabs.
- Scenes: Y'all'll find 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 than, brand sure to cheque out the TextMesh Pro tutorial.
Whew, that was a lot of folders!
Open up the TweenBreaker scene in Assets/RW/Scenes, then click Play to try this Breakout clone. Utilize the correct and left arrows or the A and D buttons on the keyboard to move the paddle. Brand the ball bounce around and break as many crates equally you wish.
At present, information technology'south 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 almost kinds of blitheness, so why would you want to bring in another parcel? Isn't information technology redundant?
The keyword here is overkill. The blitheness engine is too powerful for simpler tasks, and it may bleed precious resources from the histrion'southward computer.
Unity's Animator Component has a callback function that continuously calls for every Animator on the scene. Animating GameObjects without using the Animator Component is an excellent manner to continue requirements low.
What is Tweening?
Simplistically, tweening, or inbetweening, is some other name for interpolation. In this operation, a property can presume any value between ii limits.
For case, imagine a GameObject that translates betwixt two points in a four 2nd time interval, equally shown in the following figure:
You know the position at null seconds and 4 seconds: Equally the effigy shows, those are the points (0, 0, 0) and (1, 0, 0). Yet, to animate 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 exist at (0.five, 0, 0), at one second, at (0.25, 0, 0), at three seconds, (0.75, 0, 0) and then on. This simple interpolation creates animation using just simple algebraic operations.
It's possible to make this animation a piffling fancier past using animation curves, besides known as tweening curves. In the previous example, to go the position of an chemical element at any given time, you had to separate the total deportation past the elapsed time and add this value to the initial position.
That isn't the only way to accomplish the last value: The progression doesn't need to be uniform. It'southward time to talk over tweening curves, besides called easing functions.
In this case, the interpolation is no longer linear merely instead uses an arbitrary function to dictate how the element moves. For example, if you said the GameObject in the previous case should movement similarly to a sine function, the velocity would be lower on the extremes of the office.
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, you should consider tweening's strengths and limitations.
Tweening is neat for simple components and animations. A adept dominion of pollex is to use tweening whenever you want to breathing something straightforward without sacrificing framerate.
But trying to create complex animations solely with tweening can quickly get out of hand. The Animator Component's actress bulk and ability is amend suited for tackling these more elaborate animations, such as sprite or skeletal animation.
How much overhead is there in the Animator Component? Permit's take a moment to compare their performance.
Performance Comparison
You can utilize Unity'due south profiler to go a meliorate view of what's going on behind the scenes in this Animator and tweening comparison. To permit for a better comparison, have an example scene, with sprites moving as shown in the following effigy:
Now, consider a scene with many of those sprites making the same movement. As their number increases, the calculator requirements increase accordingly. For 300 sprites moving sideways with the animator, the Unity profiler shows:
The animator is that thick blue line.
That thick bluish line is how much processing power Unity'south Animator component is consuming. Selecting the line at a given point shows what'south happening in Unity's main loop:
Notice that the principal 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 manner to eliminate information technology…
That'due 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 near information technology:
The principal thread is different too. Take a await:
And the final animation outcome is the same. 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 Projection
To add LeanTween to your projects, go to its Asset Shop page and add together to your assets.
When y'all finish, it'll appear in your package explorer window in Unity. Select it and then click Install. When prompted, click Import to add together the package to your projection.
At present, on to using the recently added parcel in your game.
Animating the Paddle With the Tween Library
The first GameObject y'all'll breathing 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 always a reaction.
For the player to feel the activeness, the paddle needs to react to the collision. You'll apply the translation functions to displace the paddle accordingly.
Translating Objects with LeanTween
As yous already learned, you can use tweening to displace game elements for a specific amount of time. With LeanTween, the move function takes intendance of general displacement. Y'all specify the initial position, terminal position and time that the movement should accept.
However, more than specialized functions movement the GameObject in a single axis: moveX
, moveY
and moveZ
. In this tutorial, yous'll use the function specialized to move the paddle forth the Y-axis.
Billowy the Paddle
You need to add together some displacement to the paddle and make it react to the collision with the brawl. Go to Paddle.cs and supplant the entire OnCollisionEnter2D()
with:
individual void OnCollisionEnter2D(Collision2D collision) { //1 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 principal things:
- This line checks if there'south a collision betwixt the paddle and the ball (the "Cog"). In this example, the paddle tin can't collide with anything else, but it'southward adept practice to exist clear about which standoff you want to handle.
- This function tells LeanTween to stop any other furnishings that might deed on this GameObject. This step helps you avoid errors by ensuring no other blitheness 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, "motility the y-axis of the gameObject half a unit downwards, over half a second".
At present press the Play button. You'll encounter the paddle bounces upwardly and downwards for one-half a second and so returns to the initial position.
Bounciness, paddle, bounce!
However, fifty-fifty though the paddle moves forth the Y-axis, information technology goes back to its initial position in the finish. This happens because of the setEaseShake()
appended at the cease of LeanTween.moveY()
. This ease curve defines that the movement should stop at the aforementioned betoken where it started, creating the bounce effect shown on the paddle.
If y'all desire, remove setEaseShake()
and watch as the paddle gets relentlessly pounded to the bottom of the screen. Merely remember to add it back in when you lot're done.
Where are you going, paddle?
Adding Character to the Ball
In the starter project, the brawl bounces effectually, breaking the crates and bouncing off the paddle. However, you lot can make information technology a more than interesting character.
Currently, the ball animation is based solely on physics: When the ball collides, it reflects and keeps moving. But, with tweening techniques, you can make the ball a piffling more interesting.
To create some interesting graphics, begin by irresolute the scale of the ball with tweening furnishings.
Scaling the ball
All the examples thus far were about movement. However, you tin cull a value for whatever given property.
To illustrate that concept, replace OnCollisionEnter2D()
in BallScript.cs with:
private void OnCollisionEnter2D(Collision2D standoff) { if (collision.gameObject.tag.Equals("Player")) { hitPosition = (ballRigidbody.position.ten - standoff.rigidbody.position.x) / collision.collider.bounds.size.x; direction = new Vector2(hitPosition, 1).normalized; ballRigidbody.velocity = direction * BallSpeed; } // 1 LeanTween.abolish(gameObject); transform.localScale = new Vector3(0.4f, 0.4f, 0.4f); // two LeanTween.scale(gameObject, new Vector3(ane.0f, 1.0f), one.0f).setEase(LeanTweenType.punch); }
Here'south a code breakdown:
- These two lines reset the GameObject beliefs. In addition to
LeanTween.cancel()
, the ball's calibration needs to reset to avoid any error propagation. If the ball collides with some other chemical element earlier the animation ends, the beginning scale will exist incorrect, and, in the end, the "normal" size of the ball will be modified. - Once again, this is the code that actually performs the operation. This fourth dimension, however, you lot're scaling the GameObject instead of moving information technology. This scales the ball from its normal size (0.four) to i.0 and back, thanks to the
punch
easing function.
Printing the Play button. Wait at how nice the brawl behaves at present:
Personalized Easing Functions
In this example, you used a predefined easing bend for the scale performance. But setEase
isn't limited to merely LeanTweenType
easing curves.
This function as well gives you the flexibility of drawing your own curves with Unity's help. Add the following animationCurve
variable to the BallScript
class:
public AnimationCurve animationCurve;
Then, supersede:
LeanTween.scale(gameObject, new Vector3(1.0f, i.0f), 1.0f).setEase(LeanTweenType.dial);
With:
LeanTween.scale(gameObject, new Vector3(ane.0f, 1.0f), 1.0f).setEase(animationCurve);
Relieve the script changes and go to the Hierarchy window. Aggrandize the Histrion Objects GameObject, select the Cog GameObject and look at the Inspector window.
Here you can set your ain easing curve.
You'll see a new parameter that lets y'all describe your easing function graphically. You tin also select a predefined curve defined by Unity.
This is particularly helpful for testing considering you can endeavour diverse curves and behaviors for your scene elements in Play Way. Y'all tin fine-tune your game as much as you want until the game feels exactly as you intend.
For example, if y'all ready the bend to chop-chop ascend, like this:
The brawl grows quickly in the beginning, and then plateaus, like so:
Nevertheless, if the bend is inverted:
The ball will begin growing slowly and pick up momentum:
Because you lot ready the ball to reset its scale for every collision in the code, it'll work with whatsoever bend you lot choose to elaborate. However, to avoid relying on setting the size past lawmaking, y'all could try a bend that comes dorsum to the initial size in the cease later applying some scaling, like this:
Correct click the curve and add together as many keys every bit you like to create various furnishings. This curve gives the ball a rubbery feeling:
Now create your own rubbery curve and select it as the Blitheness Curve for your script.
Color-Changing Effects
In add-on to Transform-based effects, like motility and scaling, you can also add color-changing effects.
In BallScript.cs, add one more line to the end of OnCollisionEnter2D()
to allow for color effects:
gameObject.LeanColor(Colour.yellow, 0.5f).setEasePunch();
This final line makes the ball flash yellow for half a 2nd, producing the following consequence:
At present the ball is a character in the game.
In the instance of color changing, you accept the option of calling the LeanTween function straight on the GameObject, rather than having to pass the GameObject in as an statement, which is a dainty bit of syntactic carbohydrate.
Breaking the Blocks
Currently, the blocks intermission, but you could add more than interesting behaviors to the blocks after they collide with the ball.
Open up Crates.cs. Y'all'll see the code for OnCollisionEnter2D()
.
In OnCollisionEnter2D()
, y'all find only a reference to the office that increases the score as the player breaks the crates. But, y'all'll add together more momentarily.
The blocks just vanish…
Rotating Objects With LeanTween
Past now, you lot may be wondering which numbers you could interpolate side by side. In this step, you'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. Now you'll use LeanTween to add a more interesting consequence to information technology.
Supercede the entire OnCollisionEnter2D()
with:
private void OnCollisionEnter2D(Collision2D collision) { //1 gameObject.GetComponent<Collider2D>().enabled = faux; //2 LeanTween.alpha(gameObject, 0.2f, 0.6f); //iii LeanTween.rotateAround(gameObject, collision.GetContact(0).normal, 250.0f, 0.6f).setDestroyOnComplete(truthful); // Increases the score GameManager.Case.IncreaseScore(i); }
Here'due south what the code does:
- Initially, you disable the GameObject'due south collider to avert getting additional collisions between when crate is hit and when information technology finally disappears from the scene.
- To requite the illusion of the crate disappearing, yous utilise the alpha channel to subtract the element'due south opacity to 0.2 over 0.6 seconds.
-
rotateAround()
rotates the gameObject around the signal where the collision happened, 250 degrees along 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 later the animation finishes, removing the elements from the scene just after the marked operations finishes.
Now press Play and see how cool your work looks.
Much better now!
Tweening UI Elements
You've come a long way in adding animation to the project. Fifty-fifty though the private animations are simple, when everything comes together, the composition is awesome.
But if y'all look closely, y'all'll notice that not everything has dynamic beliefs.
The score text is yet static. It counts the points correctly, but there isn't much to it.
In Unity, UI elements are also GameObjects, so it should be elementary to add some furnishings, correct? Right!
How it is now.
Score Increase 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(); // i 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, 15.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, ane.5f, 0.5f).setEasePunch(); }
As this lawmaking has a few new functions, analyze it by blocks:
- This cake resets the score display GameObject's appearance. These lines finish any tweening operation interim on
scoreDisplay
and reset its rotation and calibration to avert whatever mistake propagation during gameplay. - The functions in this block add together rotation and calibration furnishings to the
scoreDisplay
GameObject. Here, y'all declare a rotation along the Z-centrality and a scale along the 10-axis, with the aforementioned easing office.
As you lot may have realized, yous tin can perform the aforementioned operations bachelor for every other GameObject on the UI elements. However, while the tweening code was encapsulated within each one, the tweening code for the score is within the GameManager
class.
Now, run the game and see your newly blithe scores add up.
Much better now!
You lot can use LeanTween to animate other elements, not just ones where yous include the script files.
Tweening the Background Color
If y'all press Play at present, you'll see that the game is complete, but at that place'due south however room for improvement. The background could respond to the game actions equally well. It'due south the perfect opportunity to go the actress mile and add a few more interesting effects to the visuals.
Before jumping into the code, aggrandize the Level Geometry GameObject in the Hierarchy window. Then select the Background GameObject and look at its properties in the Inspector Window.
Find that the Sprite Renderer component has a colour other than white. This helps create the illusion of three-dimensional space, with the background beingness at a distance from the foreground.
To act on it, you'll need a reference to the Background GameObject. So, at the summit of GameManager.cs, correct beneath:
public GameObject Paddle;
Add together two more variables to represent the reference to the Background GameObject and how much it should shake, similar this:
public GameObject Background; public bladder backgroundShakeRate = 2.0f;
Now, supercede IncreaseScore(int value)
once 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.i; LeanTween.rotateZ(scoreDisplay.gameObject, 15.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, i.5f, 0.5f).setEasePunch(); // ane LeanTween.movement(Background.gameObject, Random.insideUnitCircle * backgroundShakeRate, 0.5f).setEasePunch(); // 2 Groundwork.LeanColor(Color.cherry, 0.3f).setEasePunch().setOnComplete(() => { Background.GetComponent<SpriteRenderer>().color = new Colour(0.38f, 0.38f, 0.38f); }); }
Both move
and LeanColor
were already used for other elements. Now, you'll employ them slightly differently:
- This lawmaking uses
LeanTween.movement()
. Only in this case, the movement is performed in a random direction past usingRandom.insideUnitCircle
to return a randomVector2
inside a unit circle (a circumvolve with a radius of 1). - This code shows how to define a lambda expression to execute equally presently every bit the blitheness finishes. In this instance, the code redefines the Groundwork sprite color attribute to the default value to avoid changing the color, only like the ball size resets every animation round.
Don't forget to add together the reference you created in the script in the editor too! Elevate the Background GameObject from the Hierarchy window to the appropriate slot in the GameManager.
Now, click Play and enjoy playing your game. Look how much improve it looks compared to the initial project:
The starter projection. Feels similar it was 20 minutes agone…
The final project, it merely looks much amend.
Where to Go From Here
From here, you tin tween abroad anything!
You can download the completed project files by clicking the Download Materials push button at the pinnacle or the lesser of this tutorial and go along exploring.
Why not become 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 equally much as you like.
You can also scan the official LeanTween documentation for boosted details on the API.
I hope you enjoyed this tutorial. If you lot take questions, comments or want to testify your final project, please bring together the forums beneath!
Source: https://www.raywenderlich.com/27209746-tweening-animations-in-unity-with-leantween
Posted by: browncritheing.blogspot.com
0 Response to "How Tu Put Animation With The Same Size Unitu"
Post a Comment