欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Unity实现引导页效果

程序员文章站 2022-06-03 15:14:20
本文实例为大家分享了unity实现引导页效果的具体代码,供大家参考,具体内容如下效果图:1、创建canvas,设置rendermode=screenspace-overlay,uiscalemode...

本文实例为大家分享了unity实现引导页效果的具体代码,供大家参考,具体内容如下

效果图:

Unity实现引导页效果

1、创建canvas,设置rendermode=screenspace-overlay,uiscalemode = scalewithscreensize,
referenceresolution(x=1080,y=1920)

2、创建一个rawimage,命名为(parentgoimg),并做如下设置

Unity实现引导页效果

3、在parentgoimg下建几个rawimage,赋予想展示的图片,并做如下设置

Unity实现引导页效果

4、添加如下脚本给parentgoimg

using system.collections;
using system.collections.generic;
using unityengine;
using unityengine.eventsystems;
using dg.tweening;
using unityengine.ui;

public class asd : monobehaviour,ibegindraghandler, idraghandler,ienddraghandler
{
  /// <summary>
  /// 可移动的最大最小x轴坐标
  /// </summary>
  private float minx, maxx;
  /// <summary>
  /// 开始触摸时,算出偏移值,防止跳变
  /// </summary>
  private float offsetx;

  /// <summary>
  /// 灵敏度
  /// </summary>
  private float sensitivityx;
  /// <summary>
  /// 当前显示第几页
  /// </summary>
  private int currentshowindex = 1;

  private void start()
  {
    (transform as recttransform).pivot = new vector2(0, 0.5f);
    debug.log(screen.width + "  " + screen.height);
    for (int i = 0; i < transform.childcount; i++)
    {
      (transform.getchild(i) as recttransform).sizedelta = new vector2(0, 0);
      //canvas的rendermode要设置成overlay形式
      //这里i*1080是因为canvas的uiscalemode设置成了scalewithscreensize,resolution为x=1080,y=1920
      //如果canvas的uiscalemode设置成constantpixelsize则吧这里的i*1080改成i*screen.width
      (transform.getchild(i) as recttransform).anchoredposition = new vector2(i * 1080.0f, 0);
    }

    minx = -((transform.childcount - 1) * screen.width);
    maxx = 0.0f;
    //如果移动超过页面的五分之一,则切换页面
    sensitivityx = screen.width / 5;
  }

  public void onbegindrag(pointereventdata eventdata)
  {
    offsetx = transform.position.x - input.mouseposition.x;
  }

  public void ondrag(pointereventdata eventdata)
  {
    //将物体坐标限制在最大最小x轴坐标内
    transform.position = new vector2(input.mouseposition.x + offsetx, transform.position.y);
    if (transform.position.x <= minx)
    {
      transform.position = new vector2(minx, transform.position.y);
    }
    else if (transform.position.x >= maxx)
    {
      transform.position = new vector2(maxx, transform.position.y);
    }
  }

  public void onenddrag(pointereventdata eventdata)
  {
    //判断坐标,是否需要切换页面
    if (transform.position.x > getleftx())
    {
      currentshowindex--;
    }
    else if (transform.position.x < getrightx())
    {
      currentshowindex++;
    }
    transform.domovex(-(currentshowindex - 1) * screen.width, 0.2f);
  }

  float getleftx() {
    return -((currentshowindex - 1) * screen.width - sensitivityx);
  }

  float getrightx() {
    return -((currentshowindex - 1) * screen.width + sensitivityx);
  }
}

运行即可看到效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。