Unity core 7 - 2D animation

1. Sequence frame animation

(1) What is sequence frame animation

​ Our most common sequence frame animation is the Japanese animation we watch. Switching pictures in sequence at fixed time intervals is the essence of sequence frame animation

​ When the fixed time interval is short enough, our naked eyes will think that the picture is continuous and dynamic, and then form animation (moving picture)

​ Its essence is similar to the frame rate concept of the game. The principle is to switch the displayed pictures continuously at a certain time interval in a loop.

(2) Make sequence frame animation

​ Method 1:

  1. create an empty object

  2. create an animation

  3. Drag the sequence frame of an action directly into the window

​ Method 2:

​ Drag the picture directly into the Hierarchy layer window

​ Note: You can modify the animation frame rate to control the playback speed of the animation

2. Skeletal animation - 2D  Animation

​ 2D skeletal animation is produced using the production principles of 3D skeletal animation

​ Divide a 2D picture into n parts, tie bones to each part, control the rotation and movement of the bones, and achieve smooth 2D animation effects with the least amount of 2D art resources

​ Search for 2D Animation in the Package Manager window and install it

​ After importing the tool, there will be an option Skinning Editor in the Sprite Editor window

(1) Single picture bone editing

​ Menu bar button:

  1. Reset Pose: Returns the character's googles and joints to their original positions
  2. Sprite Sheet: Atlas display (only displayed in special image format psb)
  3. Copy: copy the currently selected data
  4. Paste: paste copied data

​ Bones: Bones

  1. Preview Pose: preview mode, you can preview the action without actually changing the settings

  2. Edit Bone: Edit the bone, you can change the bone position, length, direction, name, etc.

  3. Create Bone: To create a bone, you need to double-click the picture to select it before creating the bone

    Left click to create bones, each bone is a sub-object of the previous bone by default

    Right-click to cancel the parent-child relationship and continue to create bones

  4. Split Bone: Split the bone and divide a bone into two

​ Geometry: Skinning

​ Skinning determines which part of the bone is mainly controlled

  1. Auto Geometry: Automatic skinning
    • Outline Detail: Edge details, the larger the value, the finer the outline
    • Alpha Tolerance: Alpha tolerance value, control skinning details
    • Subdivide: degree of refinement, control skinning details
    • Weights: Whether to automatically set the weight, generally check
  2. Edit Geometry: Edit skinning
  3. Create Vertex: create a vertex
  4. Create Edge: Create an edge
  5. Split Edge: Split Edge, separates an edge with a new vertex

​ Weights: weight

​ Weights determine how vertices and edges are affected when bones move

  1. Auto Weights: Automatically assign weights
  2. Weight Slider: Edit vertex and edge weights
    • Mode: calculation mode
      • Add And Subtract: Addition and subtraction
      • Grow And Shrink: Growth and Search
      • Smooth: smooth
    • Bone: set the weight of the bone
    • Normalize: Normalize settings
    • Amount: order of magnitude
    • Vertex Weight: The bone corresponding to the vertex weight
  3. Weight Brush: Use a brush to give weight
  4. Bone Influence: Mainly used for image association using bone control points in psb images

​ After the setting is complete, drag the picture into the Hierarchy window, add the Sprite Skin script to it, click the Create Bones button, and the bones will be generated

After that, you can add animation to it through Animation

(2) Atlas picture bone editing

​ Before editing, we need to do the following operations on the picture:

  • Set Sprite to Atlas mode
  • Slice the gallery image

​ The specific bone operation for each picture in the atlas is similar to the above

​ In the Hierarchy window, create a root object as the parent object of the atlas, and drag each image into the root object in turn.

​ After dragging a picture each time, add a Sprite Skin script to it, click the Create Bones button, and the bones will be generated

​ Continue dragging into the scene according to the parent-child relationship of the picture in the atlas, you can modify the Order In Layer parameter on the Sprite Renderer component of the picture to adjust the front and back display of the picture

(3) psb picture bone editing

​ PS (photoshop) is a powerful image processing software that is widely used in various fields, and it is also one of the most used image processing software by art students in the game industry

​ PSD and PSB are two formats, both of which are the file formats used by PS software to save image processing data

​ There is not much difference between the PSD and PSB formats. The biggest difference is that the PSD format is compatible with some software other than PS, while PSB can only be opened with PS

​ It is officially recommended to use the PSB format in Unity, and the 2D PSD Importer toolkit needs to be introduced in the Packages Manager window

​ PSB file key parameters:

​ PSB file is also a picture file, so most of the parameters are consistent with the general picture parameters (see  picture import and picture settings ), here mainly explain its unique parameters

  1. Extrude Edges: The edge of the picture is extended to the grid, generally not modified
  2. Import Hidden: Whether to import hidden layers in the PSB file, generally unchecked
  3. Moszic: When enabled, generate Sprites from layers and merge them into a single texture, checked by default
  4. Character Rig: whether to enable the bound bones of the character, checked by default
  5. Use Layer Grouping: Use layer grouping in PSB files
  6. Pivot: pivot point position
  7. Reslice: Regenerates the sprite from the imported layer and clears any changes to the sprite, only useful if Moszic is enabled
  8. Keep Duplicate Name: Let the Sprite name retain the name in the PSB file

​ Bone editing interface changes:

​ When generating the skin for each layer, the bones of other layers may be covered. At this time, you can set the affected bones in the Bone Influence option interface

3. Inverse Kinetics IK

​ In skeletal animation, the method of building bones is called forward dynamics, and its manifestation is that the position of the child bone (joint) changes according to the rotation of the parent bone (joint)

​Using our human body as an example, when we raise our arms, it is the movement of the entire arm driven by the shoulder joint. If we understand it with the bones of father and son, it means that the father drives the child.

​ The full name of IK is Inverse Kinematics, which translates to the meaning of inverse dynamics

It is the exact opposite of forward dynamics. Its manifestation is that the position change of the end of the child bone (joint) will drive itself and its parent bone (joint) to rotate

​ Take our human body as an example. When we pick up a cup, we use the palm of our hand to hold it. Taking the cup as a reference, we move the position of the cup, and the arm will move with the cup.

​ If you understand it with the father-son skeleton, the son drives the father

​ To introduce the 2D IK toolkit in the Package Manager window, you need to select Show preview packages in the Advanced option, so that you can see the 2D IK related content

​ Note: If an error is reported when importing the package, you need to add inbound rules in Windows Firewall

(1) IK Manager 2D

​ Drag the PSB file from the previous section into the Hierarchy window, create a parent object Player for it to facilitate management, and add an IK Manager 2D script to the Player

  1. IK Solvers: IK solver, add IK here
    • Chain (CCD): It can be customized to affect N joint points, and cannot be reversed
    • Chain (FABRIK): can be customized to affect N joint points, and can be reversed
    • Limb: only affects 3 joint points, generally used to control limbs
  2. Weight: weight, when there are multiple IKs controlling the same point, the weight will affect the percentage of control
  3. Restore Default Pose: restore the default position

​ After the addition is complete, create a new empty object IK for the bone that needs to add the IK effect, and move its position to the end of the bone

​ Click the plus sign in the IK Manager 2D script to create a new IK object, and you will find that there is an additional IK object under the Player and the corresponding script is mounted

(2) CCD Solver 2D

  1. Effector: Default IK point position
  2. Target: the IK object generated according to the position of the IK point,
  3. Chain Length: IK affects the number of bones. After the setting is successful, you will find that the linked bones will have a green circle
  4. Iterations: The number of times the algorithm runs, generally not modified
  5. Tolerance: the degree of fault tolerance, generally not modified
  6. Velocity: speed, generally not modified
  7. Constrain Rotation: Constrain the degree of rotation
  8. Solve from Default Pose: Solve calculations from the default pose
  9. Weight: weight

​ After setting the parameters, click Create Target, and the Target will be created on the sub-object of the object mounted by the script and automatically associated

(3) Fabrik Solver 2D

  1. Effector: Default IK point position
  2. Target: the IK object generated according to the position of the IK point,
  3. Chain Length: IK affects the number of bones. After the setting is successful, you will find that a green circle will appear on the associated bones (the color can be set)
  4. Iterations: The number of times the algorithm runs, generally not modified
  5. Tolerance: the degree of fault tolerance, generally not modified
  6. Constrain Rotation: Constrain the degree of rotation
  7. Solve from Default Pose: Solve calculations from the default pose
  8. Weight: weight

(4) Limb Solver 2D

  1. Effector: Default IK point position
  2. Target: the IK object generated according to the position of the IK point,
  3. Flip: Reverse rotation, used to control the rotation direction of IK
  4. Constrain Rotation: Constrain the degree of rotation
  5. Solve from Default Pose: Solve calculations from the default pose
  6. Weight: weight

​ The usefulness of IK:

  • aiming function
  • head facing function
  • pick up function

​ For directional functions, we can use IK to achieve the maximum effect, which can facilitate our animation production

Four, dress up

(1) Create a dress-up resource in the same psb file

  • When making art resources in ps, place all the dress-up resources of a game object in a good position
  • When we import this resource, we should pay attention to whether the hidden layer is imported

​ Set the classification for each layer on the Visibility panel on the right, and the label on the right is equivalent to its name in the classification

​ Notes:

  • The bones associated with each part must be explicitly set
  • Group different equipment for the same part

​ After the bone and skin settings are completed, import the picture into the scene, and you will find that it automatically adds the Sprite Library, which is used to determine the category grouping information

​ At the same time, Unity will add a sprite solver Sprite Resolver for each type of equipment set, which is used to determine the part type and the picture used

​ Example of using code to change clothes:

using UnityEngine.Experimental.U2D.Animation;

private Dictionary<string, SpriteResolver> equipDic = new Dictionary<string, SpriteResolver>();

// 1.获取各部位的SpriteResolver(需要引用命名空间)
// 2.使用SpriteResolver的API进行装备切换
// GetCategory() 获取当前部位默认的类别名
// SetCategoryAndLabel 设置当前部位想要切换的图片信息

private void Start() {
    SpriteResolver[] srs = this.GetComponentsInChildren<SpriteResolver>();
    for (int i = 0; i < srs.Length; i++) {
        equipDic.Add(srs[i].GetCategory(), srs[i]);
    }

    ChangeEquip("Cask", "CASK 1");
}

public void ChangeEquip(string category, string equipName) {
    if (equipDic.ContainsKey(category)) {
        equipDic[category].SetCategoryAndLabel(category, equipName);
    }
}

(2) Make dress-up resources in different psb files

​ Guarantee the unity of each part in the PS file, and the basic parts can be selectively hidden

Note: The bone information of different files must be unified, so we directly use the copy method

1. First create a Sprite Library Asset data file and set its parameters


2. Add Sprite Library to the root object and associate data files

3. Associate the Sprite Resolver for the replacement part

​ Games with fewer outfit changes, such as only facial expressions, can use the same psb file scheme

​ For games with many outfit changes, for example, there are n types of equipment in each part, different psb file schemes can be used, and the scalability is stronger

​ Everything depends on the needs

Five, skeletal animation -  Spine

​ Spine is a paid cross-platform 2D skeletal animation production tool, which supports Unity, UE, Cocos2D, Cocos2D-x and other game engines

​ Compared with the 2D Animation launched by Unity in 2018, Spine is a stable and efficient skeletal animation production solution commonly used in commercial games

​ Official address: http://zh.esotericsoftware.com/

​ Making skeletal animations is the job of artists, unless you are making an independent game, the art program is packaged by one person, then we don't need to learn how to make skeletal animations through Spine

​ We just need to learn how to use the resources made by Spine programmatically in Unity

​ If you want to learn how to make Spine skeletal animation, you can learn according to the teaching content provided by the official website

​ With the runtime library provided by Spine that supports Unity development, we can use the skeletal animation made by Spine in Unity.
You can simply understand that it is actually the code written by the official to identify the file and process the rendering effect of the file.
We only need to learn how to use it. The API it provides is

(1) Use of skeletal animation

​ The resources exported by Spine have 3 files:

  • .json stores bone information
  • .png image atlas used
  • .atlas.txt The location information of the image in the atlas

​ When we import these three resources into the Unity project that has introduced the Spine runtime, it will be automatically generated for us:

  • _Reference configuration files for Atlas materials and .atlas.txt files
  • _Material material file
  • Reference configuration files for _Skeleton Data, json and _Atlas resources

​ Two ways to create animations:

1. Drag the _Skeleton Data file directly into the scene and choose to create a Skeleton Animation object

2. Create an empty object, and then manually add the script Skeleton Animation for association

(2) Skeletal animation parameters

​ Skeleton data file:

  1. Skeleton JSON: bone data file
  2. Scale: zoom size
  3. Skeleton Data Modifiers: bone data modifier
  4. Blend Mode Materials: Blend Mode Materials
  5. Apply Additive Material: Whether to use superimposed materials
  6. Additive Material: Overlay material
  7. Multiply Material: multiplied material
  8. Screen Material: screen material
  9. Atlas Assets: Atlas Assets
  10. Mix Setting: mixing settings
    • Animation State Data: animation state data
    • Default Mix Duration: default mixing duration
    • Add Custom Mix: Add a custom mix
  11. Animations: animation
  12. Setup Pose: Set up the pose
  13. Create Animation Reference Assets: Create animation reference assets
  14. Slots: Slots, a part has multiple pictures, you can preview it here
  15. Skeleton Mecanim: bone control
  16. Controller: associated animation controller

​ Skeletal animation script:

  1. Skeleton Data Asset: associated skeletal animation information

  2. Sorting Layer: where the sorting layer

  3. Order in Layer: the serial number of the sorting layer

  4. Mask Interaction: The way to interact with the sprite mask

    • None: Do not interact with any sprite masks in the scene
    • Visible Inside mask: The place covered by the sprite mask is visible, but the outside of the mask is invisible
    • Visible Outside mask: The place outside the sprite mask is visible, but the mask coverage is invisible
  5. Advanced: Advanced settings, generally do not modify, just understand

    • Initial Flip X/Y: Initial Flip X/Y
    • Update When Invisible: Whether to update when invisible
      • Nothing: no update
      • Only Animation Status: only animation status
      • Only Event Timelines: Only events
      • Everything Excepts Mesh: Update everything except the mesh
      • Full Update: Update all
    • Use Single Submesh: Use a single submesh
    • Fix Draw Order: Fixed drawing order
    • Immutable Triangles: constant triangle
    • Clear State On Disable: Clear state when disabled
    • Separator Slot Names: Separator slot name
    • Z Spacing: Z spacing
    • Vertex Data: vertex data
      • PMA Vertex Colors: PMA vertex colors
      • Tint Black: light black
      • Add Normals: Add normals
      • Solve Tangents: Solve Tangents
    • Add Skeleton Utility: Add skeleton utility
  6. Animation Name: the name of the currently playing animation

  7. Loop: whether to loop

  8. Initial Skin: initial skin

    Art may have several sets of skins during production, and generally only one set is needed

  9. Time Scale: Time scaling, the larger the value, the faster the animation will play

  10. Root Motion: Whether to add root motion scripts, generally not

(3) Skeletal animation code

using Spine;
using Spine.Unity;
using UnityEngine;

private SkeletonAnimation sa;

[SpineAnimation] // 可以在Unity面板中选择动画,而不是填入字符串
public string jumpName;

[SpineBone]  // 可以在Unity面板中选择骨骼,而不是填入字符串
public string boneName;

[SpineSlot]  // 可以在Unity面板中选择部位,而不是填入字符串
public string slotName;

[SpineAttachment]  // 可以在Unity面板中选择附件,而不是填入字符串
public string attachmentName;

// Start is called before the first frame update
void Start() {
    sa = this.GetComponent<SkeletonAnimation>();

    // 动画播放
    
    // 方法一:直接改变SkeletonAnimation中参数
    // 需要先改循环为false后再设置动画
    sa.loop = true;
    sa.AnimationName = "jump";

    // 方法二:使用SkeletonAnimation中动画状态改变的函数
    // 马上播放
    sa.AnimationState.SetAnimation(0, jumpName, false);
    // 排队播放
    sa.AnimationState.AddAnimation(0, "walk", true, 0);

    // 转向

    sa.skeleton.ScaleX = -1;

    // 动画事件

    // 动画开始播放
    sa.AnimationState.Start += (t) => { print(sa.AnimationName + "动画开始播放"); };
    // 动画被中断或者清除
    sa.AnimationState.End += (t) => { print(sa.AnimationName + "动画中断或者清除"); };
    // 播放完成
    sa.AnimationState.Complete += (t) => { print(sa.AnimationName + "动画播放完成"); };
    // 做动画时添加的自定义事件
    sa.AnimationState.Event += (t, e) => { print(sa.AnimationName + "自定义事件"); };

    // 便捷特性

    // 动画特性 [SpineAnimation]  
    // 骨骼特性 [SpineBone]       
    // 插槽特性 [SpineSlot]       
    // 附件特性 [SpineAttachment] 

    // 获取骨骼、设置插槽附件

    // 获取骨骼
    Bone b = sa.skeleton.FindBone(boneName);
    sa.skeleton.SetAttachment(slotName, attachmentName);

    // 在UI中使用
    // SkeletonGraphic(UnityUI)
}

Guess you like

Origin blog.csdn.net/weixin_53163894/article/details/131307154