Unity—平滑的帧动画

旧的方法

直接在update中每帧切换图片资源的话,动画显示会很硬直。

实现效果

请添加图片描述

资源处理

请添加图片描述

  1. 将8*4的png图片导入到工程中,Texture Type设置为Editor GUI and Legacy GUI或者Sprite
  2. 新建一个材质球,Shader设置为Legacy Shaders/Particles/Additive或者Mobile/Particles/Additive
    在这里插入图片描述

UI组件

  1. Cavnas下新建一个Image组件在这里插入图片描述
  2. 将目标Image组件的Material改为新建的材质
  3. 在这里插入图片描述

组件代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LoopTings : MonoBehaviour
{
    Image _img;
    Material _material;

    float startTime;

    [Header("X轴图片数量")]
    public int countX = 8;
    [Header("Y轴图片数量")]
    public int countY = 8;

    public float _speed = 26f;

#if UNITY_EDITOR
    private void OnValidate()
    {
        _material = transform.GetComponent<Image>().material;
		// 设置平铺和偏移
        Vector2 inital = new Vector2((1f / countX), (1f / countY));
        _material.mainTextureScale = inital;
        _material.mainTextureOffset = inital;
    }
#endif

    // Start is called before the first frame update
    void Start()
    {
        _img = transform.GetComponent<Image>();
        _material = _img.material;
        startTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        updateOffset();
    }

    void updateOffset()
    {
        float index = (Time.time - startTime) * _speed;
        if ((index <= (countX * countY)))
        {
            index = index % (countX * countY);
            Debug.Log(">>" + index);
            if (index == (countX * countY))
            {
                startTime = Time.time;
                index = 0;
            }
			// 小图尺寸
            Vector2 size = new Vector2(1.0f / countX, 1.0f / countY);
			// 计算索引
            float uIndex = Mathf.Floor(index % countX);
            float vIndex = Mathf.Floor(index / countX);
			// 计算偏移值
            Vector2 offset = new Vector2(uIndex * size.x, 1.0f - size.y - vIndex * size.y);
			// 设置偏移
            _material.SetTextureOffset("_MainTex", offset);
        }
        else
        {
        	// 重置
            startTime = Time.time;
        }
    }
}

设置组件

将代码丢给目标Image,根据图片大小设置对应数值。
在这里插入图片描述
因为图片是8*4个小图组成。所以X轴数量设8,Y轴数量设4。同样适用于3x3或者8x8的图。
速度自己改下就知道效果啦。

备注

免费的视频转GIF网址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值