[Unity study notes] animation system (continued) and events

In the last note, we used Unity's animation system to realize the animation of moving and jumping. In this note, we will use the way of Unity events to realize the animation of injury and death.

First create an injury animation. Since there is no ready-made injury animation in the asset, we can only manually create a simple flicker animation. The main reality is the effect of the character flickering during the invincible time after the character is injured.

Steps: Create a new animation clip. Click Add Property to add the Color in the Sprite.

Adjust the key frame so that the animation often changes to 1 second.

At 0.5 seconds, we modify Color.a to 0.5, thus realizing the flickering animation of the character.

At the same time, the characters can be adjusted to red, which is more in line with common perception.

Next, we create a new layer in the animation controller, adjust its weight to 1, and change the blending mode to Addictive.

Because we use the time method to trigger the animation this time, a new condition parameter hurt has been created.

If hurt is triggered, execute the corresponding event.

 We need to manually add UnityEvents, which is included in UnityEngine.Events, and the namespace needs to be referenced before use.

Add injury and death events:


    [Header("事件")]

    public UnityEvent<Transform> onTakeDamage;

    public UnityEvent onDie;

Go back to unity to check it out.

You can see that our events have been displayed in the Inspector window.

Click the plus sign to add the corresponding method, which will be called when the event is triggered.

So how can we trigger the event? Back to our script file, the event can be triggered by the Invoke() method.

onDie?.Invoke();

Once the event is triggered, all methods under it will be executed.

Then start to set the conditions of the injury animation. Once injured, the condition parameter hurt needs to be triggered. We need to use SetTrigger() to realize this function.

    public void PlayHurt()
    {
        anim.SetTrigger("hurt");
    }

Encapsulate it into a method and add it to the event. The passing of the hurt parameter occurs as the event occurs.

In this way, the injury animation is realized.

The production steps of death animation and injury animation are the same.

First add the condition parameter die, bind the death event, trigger the event, play the death animation, and do not repeat the demonstration.

At the same time, we can also add events in animation clips. Unity has automatically written templates for us, which is convenient for us to implement various methods when the animation starts, the animation is playing, and the animation ends.

Name the script file and open it.

Uncomment according to the prompts and add the required code.

Guess you like

Origin blog.csdn.net/qq_65021355/article/details/130330451