栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity中实现UI翻转

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Unity中实现UI翻转

一:效果演示


二:使用


FlipType:翻转类型(水平翻转、竖直翻转、水平竖直翻转)


三:实现原理

为什么尽量避免使用将Scale设置为-1
将Scale的x、y设置为-1也可以实现翻转的效果,但是这样还会影响到子物体以及animation,所以最佳的方法是修改图片网格的绘制,我们可以继承UGUI提供的网格效果基类BaseMeshEffect修改网格顶点去实现翻转效果

通过修改顶点位置实现翻转
UGUI源码解析——BaseMeshEffect


四:代码实现
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

/// 
/// 翻转
/// 
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("LFramework/UI/Effects/Flip", 3)]
public class Flip : BaseMeshEffect
{
    protected Flip()
    {

    }

    /// 
    /// 翻转类型
    /// 
    public enum EFlipType
    {
        Horizontal,
        Vertical,
        HorizontalAndVertical,
    }

    //翻转类型
    [SerializeField]
    EFlipType m_FlipType;
    public EFlipType FlipType
    {
        get
        {
            return m_FlipType;
        }
        set
        {
            m_FlipType = value;
            graphic.SetVerticesDirty();
        }
    }

    //顶点缓存
    List vertexCache = new List();

    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
        {
            return;
        }

        vh.GetUIVertexStream(vertexCache);

        ApplyFlip(vertexCache, graphic.rectTransform.rect.center);

        vh.Clear();
        vh.AddUIVertexTriangleStream(vertexCache);
        vertexCache.Clear();
    }

    void ApplyFlip(List vertexCache, Vector2 pivot)
    {
        int vertexCount = vertexCache.Count;
        for (int i = 0; i < vertexCount; i++)
        {
            UIVertex veretx = vertexCache[i];
            if (m_FlipType == EFlipType.HorizontalAndVertical)
            {
                veretx.position.x = 2 * pivot.x - veretx.position.x;
                veretx.position.y = 2 * pivot.y - veretx.position.y;
            }
            else if (m_FlipType == EFlipType.Horizontal)
            {
                veretx.position.x = 2 * pivot.x - veretx.position.x;
            }
            else if (m_FlipType == EFlipType.Vertical)
            {
                veretx.position.y = 2 * pivot.y - veretx.position.y;
            }
            vertexCache[i] = veretx;
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898357.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号