How To Change Animation When Collision Unity
When making games, you oftentimes demand to animate on-screen elements to create a narrative or add that special smoothen to capture the player'south interest. In the latter case, these effects' merely purpose is to make the experience enjoyable.
Unity has a powerful and convenient animation engine that lets you animate annihilation your heart desires. However, some types of animation, specially the nigh simple ones, don't need the full power of the animation engine. You can perform them more efficiently with a more than straightforward approach: Tweening techniques.
In this tutorial, y'all'll learn about tweening and how to:
- Use tweening in GameObjects, such every bit assets and UI.
- Integrate the LeanTween package in your project.
- Apply rotation, displacement and calibration effects to GameObjects in your projects.
- Add tweening UI elements to your projects.
By the fourth dimension you're done, you'll think almost animations not only in terms of Unity'southward Animator merely using other types of packages as well. Every bit a bonus, the final sample project will look keen!
Getting Started
Click the Download Materials push at the top or bottom of the tutorial to download the starter projection. This project requires Unity 2020.3.20f1 or later.
In Avails/RW, you lot'll find the assets used in this project. Wait at the folder structure:
- Input: Files used by Unity'southward new input arrangement.
- Physics Materials: The physics materials used for the ball in the projection.
- 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: You'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 yous create the UI. To acquire more, brand 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 attempt this Breakout clone. Use the correct and left arrows or the A and D buttons on the keyboard to move the paddle. Make the ball bounce around and break every bit many crates as you wish.
Now, it's fourth dimension to take a closer look at tweening.
Why Not Employ Unity's Animator for Everything?
That'southward a great question!
Unity already has a module capable of implementing most kinds of animation, then why would y'all want to bring in another package? Isn't it redundant?
The keyword here is overkill. The animation engine is too powerful for simpler tasks, and information technology may drain precious resources from the actor'southward estimator.
Unity'southward Animator Component has a callback function that continuously calls for every Animator on the scene. Animating GameObjects without using the Animator Component is an fantabulous way to keep requirements low.
What is Tweening?
Simplistically, tweening, or inbetweening, is another name for interpolation. In this performance, a property can assume any value between two limits.
For example, imagine a GameObject that translates betwixt two points in a iv second fourth dimension interval, as shown in the post-obit figure:
You know the position at zero seconds and 4 seconds: Equally the figure shows, those are the points (0, 0, 0) and (1, 0, 0). However, to animate it properly, the calculator needs to draw each frame.
Past getting values between those points, the animation engine tin determine that at two seconds, the GameObject should be at (0.5, 0, 0), at i second, at (0.25, 0, 0), at three seconds, (0.75, 0, 0) and and so on. This simple interpolation creates animation using merely simple algebraic operations.
It'southward possible to make this animation a little fancier by using animation curves, besides known as tweening curves. In the previous example, to go the position of an element at any given time, you had to divide the full displacement past the elapsed fourth dimension and add this value to the initial position.
That isn't the only manner to attain the terminal value: The progression doesn't need to exist uniform. It's fourth dimension to discuss tweening curves, also called easing functions.
In this example, the interpolation is no longer linear merely instead uses an arbitrary function to dictate how the chemical element moves. For case, if you said the GameObject in the previous example should motion similarly to a sine function, the velocity would be lower on the extremes of the role.
For more information on easing functions and their effects, check this reference.
Animator Component vs Tweening Techniques
When yous're choosing between the ii techniques, you should consider tweening'southward strengths and limitations.
Tweening is great for simple components and animations. A good rule of thumb is to use tweening whenever y'all desire to animate something straightforward without sacrificing framerate.
Only trying to create complex animations solely with tweening can rapidly go out of hand. The Animator Component's actress bulk and power is better suited for tackling these more elaborate animations, such equally sprite or skeletal animation.
How much overhead is there in the Animator Component? Let's take a moment to compare their functioning.
Performance Comparison
You can employ Unity'south profiler to get a better view of what's going on backside the scenes in this Animator and tweening comparison. To let for a improve comparison, take an instance scene, with sprites moving equally shown in the following effigy:
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:
That thick bluish line is how much processing ability Unity's Animator component is consuming. Selecting the line at a given point shows what'southward happening in Unity'southward primary loop:
Discover that the primary villain hither is the Animator.Update()
method. It'due south taking a lot of the main thread processing time. If only there were a mode to eliminate it…
That's where LeanTween enters. LeanTween is a bundle that provides a lean, lightweight tweening implementation. Without the demand to invoke the Animator, the whole process changes dramatically. See what the Unity profiler has to say about it:
The main thread is different also. Take a expect:
And the final blitheness effect is the same. This demonstration proves that eliminating the Animator Component from simpler animations makes it possible to boost performance and heighten your complex animations.
Adding LeanTween to Your Projection
To add together LeanTween to your projects, go to its Asset Shop folio and add to your assets.
When you terminate, it'll announced in your package explorer window in Unity. Select it and and then click Install. When prompted, click Import to add together the package to your project.
Now, on to using the recently added package in your game.
Animating the Paddle With the Tween Library
The starting time GameObject you'll breathing is the paddle. Initially, the paddle doesn't react to the ball collisions, which doesn't seem realistic. Subsequently all, when things hit each other in existent life, at that place's always a reaction.
For the thespian to feel the action, the paddle needs to react to the collision. You'll use the translation functions to readapt the paddle accordingly.
Translating Objects with LeanTween
Every bit yous already learned, you tin can apply tweening to readapt game elements for a specific amount of time. With LeanTween, the move part takes care of general displacement. You specify the initial position, final position and fourth dimension that the movement should take.
All the same, more specialized functions movement the GameObject in a single axis: moveX
, moveY
and moveZ
. In this tutorial, you'll employ the function specialized to move the paddle along the Y-axis.
Bouncing the Paddle
Yous need to add some displacement to the paddle and make it react to the standoff with the ball. Become to Paddle.cs and replace the unabridged OnCollisionEnter2D()
with:
private void OnCollisionEnter2D(Collision2D collision) { //one if (collision.gameObject.tag.Equals("Cog")) { //ii LeanTween.cancel(gameObject); //3 LeanTween.moveY(gameObject, transform.position.y - 0.5f, 0.5f).setEaseShake(); } }
This code does 3 main things:
- This line checks if there'south a standoff between the paddle and the ball (the "Cog"). In this case, the paddle can't collide with anything else, but information technology'south skilful practice to be clear about which collision you lot want to handle.
- This function tells LeanTween to stop any other furnishings that might act on this GameObject. This footstep helps you avoid errors by ensuring no other animation result operates simultaneously on the element.
- Finally, this is the line that really creates move. If information technology were a sentence in English, this part would say, "motility the y-centrality of the gameObject one-half a unit downwards, over half a second".
Now press the Play button. You'll see the paddle bounces up and downwardly for one-half a second and then returns to the initial position.
However, even though the paddle moves along the Y-centrality, it goes back to its initial position in the terminate. 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 signal where it started, creating the bounce outcome shown on the paddle.
If you want, remove setEaseShake()
and picket as the paddle gets relentlessly pounded to the bottom of the screen. Just remember to add together it dorsum in when you lot're washed.
Adding Character to the Ball
In the starter project, the brawl bounces effectually, breaking the crates and bouncing off the paddle. However, you can make information technology a more interesting character.
Currently, the ball animation is based solely on physics: When the ball collides, it reflects and keeps moving. Merely, with tweening techniques, you can make the ball a footling more than interesting.
To create some interesting graphics, begin past changing the scale of the ball with tweening effects.
Scaling the brawl
All the examples thus far were near move. Yet, yous 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.ten - standoff.rigidbody.position.x) / collision.collider.premises.size.x; direction = new Vector2(hitPosition, 1).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, one.0f), ane.0f).setEase(LeanTweenType.punch); }
Here's a code breakdown:
- These two lines reset the GameObject behavior. In addition to
LeanTween.cancel()
, the ball's scale needs to reset to avert any mistake propagation. If the brawl collides with another chemical element before the animation ends, the beginning calibration will be incorrect, and, in the stop, the "normal" size of the ball will be modified. - Again, this is the code that actually performs the functioning. This fourth dimension, however, you're scaling the GameObject instead of moving it. This scales the ball from its normal size (0.4) to 1.0 and back, thanks to the
dial
easing function.
Press the Play button. Await at how squeamish the ball behaves now:
Personalized Easing Functions
In this instance, y'all used a predefined easing curve for the scale operation. Just setEase
isn't express to only LeanTweenType
easing curves.
This office also gives y'all the flexibility of drawing your ain curves with Unity'due south help. Add together the following animationCurve
variable to the BallScript
class:
public AnimationCurve animationCurve;
And then, supplant:
LeanTween.scale(gameObject, new Vector3(1.0f, 1.0f), 1.0f).setEase(LeanTweenType.punch);
With:
LeanTween.scale(gameObject, new Vector3(1.0f, 1.0f), 1.0f).setEase(animationCurve);
Salve the script changes and go to the Hierarchy window. Expand the Player Objects GameObject, select the Cog GameObject and wait at the Inspector window.
You'll see a new parameter that lets y'all draw your easing function graphically. You tin also select a predefined curve defined by Unity.
This is particularly helpful for testing because you tin try various curves and behaviors for your scene elements in Play Mode. Y'all can fine-tune your game as much every bit you want until the game feels exactly as you intend.
For instance, if you ready the curve to apace ascend, similar this:
The ball grows quickly in the beginning, and then plateaus, similar and then:
Notwithstanding, if the curve is inverted:
The brawl volition begin growing slowly and option up momentum:
Considering you prepare the ball to reset its scale for every standoff in the code, it'll work with whatsoever curve you lot cull to elaborate. However, to avert relying on setting the size by lawmaking, you lot could endeavor a curve that comes back to the initial size in the end after applying some scaling, like this:
Right click the bend and add equally many keys as you like to create diverse furnishings. This bend gives the ball a rubbery feeling:
At present create your ain rubbery curve and select information technology as the Animation Bend for your script.
Color-Irresolute Effects
In addition to Transform-based effects, like movement and scaling, you tin also add color-irresolute effects.
In BallScript.cs, add one more line to the end of OnCollisionEnter2D()
to allow for color effects:
gameObject.LeanColor(Color.yellowish, 0.5f).setEasePunch();
This terminal line makes the ball flash yellow for half a second, producing the following effect:
In the case of colour changing, y'all have the option of calling the LeanTween function directly on the GameObject, rather than having to pass the GameObject in equally an argument, which is a squeamish bit of syntactic sugar.
Breaking the Blocks
Currently, the blocks suspension, but y'all could add together more interesting behaviors to the blocks after they collide with the ball.
Open Crates.cs. Yous'll see the code for OnCollisionEnter2D()
.
In OnCollisionEnter2D()
, y'all notice just a reference to the function that increases the score every bit the player breaks the crates. But, you'll add more momentarily.
Rotating Objects With LeanTween
By now, you may exist wondering which numbers you could interpolate next. In this step, yous'll employ tweening on rotations to create a destroy blitheness for the crates.
In the original code, when the ball collides with the crates, it only disappears. Now you lot'll use LeanTween to add a more interesting event to it.
Replace the entire OnCollisionEnter2D()
with:
individual void OnCollisionEnter2D(Collision2D collision) { //i gameObject.GetComponent<Collider2D>().enabled = fake; //2 LeanTween.alpha(gameObject, 0.2f, 0.6f); //3 LeanTween.rotateAround(gameObject, collision.GetContact(0).normal, 250.0f, 0.6f).setDestroyOnComplete(true); // Increases the score GameManager.Instance.IncreaseScore(1); }
Hither's what the code does:
- Initially, y'all disable the GameObject's collider to avoid getting additional collisions between when crate is hit and when it finally disappears from the scene.
- To give the illusion of the crate disappearing, you lot use the alpha channel to decrease the element's opacity to 0.2 over 0.6 seconds.
-
rotateAround()
rotates the gameObject around the bespeak where the collision happened, 250 degrees forth 0.half-dozen seconds. This creates a more responsive feel every bit the crate rotates around the point of contact between itself and the brawl. And so, the code tells LeanTween to destroy the GameObject after 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.
Tweening UI Elements
You lot've come a long way in calculation blitheness to the project. Even though the individual animations are simple, when everything comes together, the limerick is crawly.
Merely if you expect closely, yous'll find that not everything has dynamic behavior.
The score text is withal static. It counts the points correctly, merely at that place isn't much to it.
In Unity, UI elements are also GameObjects, and so it should be simple to add some furnishings, right? Right!
Score Increase Animation
The GameManager has a reference to the text object and is responsible updating the score.
In GameManager.cs, notice and replace the entire IncreaseScore(int value)
with:
public void IncreaseScore(int value) { gameScore += value; scoreDisplay.text = gameScore.ToString(); // one LeanTween.abolish(scoreDisplay.gameObject); scoreDisplay.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f); scoreDisplay.transform.localScale = Vector3.1; // ii LeanTween.rotateZ(scoreDisplay.gameObject, 15.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, 1.5f, 0.5f).setEasePunch(); }
As this code has a few new functions, analyze it by blocks:
- This block resets the score display GameObject'south appearance. These lines terminate any tweening operation acting on
scoreDisplay
and reset its rotation and scale to avoid any error propagation during gameplay. - The functions in this block add rotation and scale effects to the
scoreDisplay
GameObject. Here, you lot declare a rotation along the Z-centrality and a scale along the Ten-axis, with the same easing function.
Every bit you may have realized, you can perform the aforementioned operations available for every other GameObject on the UI elements. Even so, while the tweening code was encapsulated inside each i, the tweening code for the score is within the GameManager
class.
Now, run the game and see your newly blithe scores add up.
You can use LeanTween to animate other elements, not just ones where you include the script files.
Tweening the Background Color
If you press Play at present, you'll run across that the game is complete, but in that location's still room for improvement. The background could respond to the game actions equally well. Information technology's the perfect opportunity to go the actress mile and add together a few more than interesting furnishings to the visuals.
Before jumping into the code, aggrandize the Level Geometry GameObject in the Hierarchy window. Then select the Groundwork GameObject and look at its properties in the Inspector Window.
Detect that the Sprite Renderer component has a colour other than white. This helps create the illusion of 3-dimensional infinite, with the background beingness at a distance from the foreground.
To act on it, you'll need a reference to the Groundwork GameObject. And then, at the top of GameManager.cs, correct beneath:
public GameObject Paddle;
Add together two more variables to represent the reference to the Background GameObject and how much information technology should shake, like this:
public GameObject Background; public float backgroundShakeRate = two.0f;
Now, supervene upon 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, fifteen.0f, 0.5f).setEasePunch(); LeanTween.scaleX(scoreDisplay.gameObject, 1.5f, 0.5f).setEasePunch(); // ane LeanTween.move(Background.gameObject, Random.insideUnitCircle * backgroundShakeRate, 0.5f).setEasePunch(); // two Background.LeanColor(Colour.red, 0.3f).setEasePunch().setOnComplete(() => { Background.GetComponent<SpriteRenderer>().color = 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.move()
. Just in this example, the motility is performed in a random direction by usingRandom.insideUnitCircle
to return a randomVector2
within a unit circle (a circle with a radius of 1). - This code shows how to define a lambda expression to execute as soon as the blitheness finishes. In this instance, the code redefines the Background sprite color attribute to the default value to avoid changing the colour, just similar 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 relish playing your game. Expect how much better it looks compared to the initial project:
Where to Get From Here
From here, you can tween away annihilation!
You can download the completed project files by clicking the Download Materials push at the top or the bottom of this tutorial and go on exploring.
Why not get a experience for creating your custom ease curves in the Unity Editor? Try replacing some easing functions for the elements in the project and change them as much as you like.
Y'all can as well browse the official LeanTween documentation for additional details on the API.
I hope you enjoyed this tutorial. If you have questions, comments or want to show your last project, delight bring together the forums below!
Source: https://www.raywenderlich.com/27209746-tweening-animations-in-unity-with-leantween
Posted by: browngribetwouter.blogspot.com
0 Response to "How To Change Animation When Collision Unity"
Post a Comment