鼠标拖拽,通过计算鼠标坐标和按下时的坐标判断播放的序列帧,一定时间无操作自动播放序列。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RotateBuildnew : MonoBehaviour
{
//序列载体
public Image image;
//序列
public Sprite[] sprit_arr;
//当前序列位置
private int index;
private float oriX;
private int offset;
private int currentIndex = 0;
//速度控制
private int delta = 10;
//无操作时间
private float noOperate = 0;
//是否开始计时
private bool isTime = true;
//是否允许自动播放
public bool isCanRoate = false;
private void OnEnable()
{
image.sprite = sprit_arr[0];
currentIndex = 0;
}
// Update is called once per frame
void Update()
{
//鼠标拖拽播放序列
if (Input.GetMouseButtonDown(0))
{
//停止自动播放
StopCoroutine("onAutoRotate");
//更新当前图片的序列位置
currentIndex = index;
//记录当前鼠标位置
oriX = Input.mousePosition.x;
}
if (Input.GetMouseButton(0))
{
//计算当前鼠标坐标和按下鼠标时的差值
offset = (int)(Input.mousePosition.x - oriX);
//控制速度
if (offset != 0)
{
offset = offset / delta;
}
//计算序列帧数
index = currentIndex + offset;
if (index > 0)
{
index = index % sprit_arr.Length;
}
if (index < 0)
{
index = Math.Abs(index);
index = index % sprit_arr.Length;
index = sprit_arr.Length - index;
if (index == sprit_arr.Length)
{
index = 0;
}
}
//更新图片
image.sprite = sprit_arr[index];
}
if (Input.GetMouseButtonUp(0))
{
//更新当前图片的序列位置
currentIndex = index;
}
//是否允许自动播放序列
if(isCanRoate)
{
//拖拽时停止计时
if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0))
{
noOperate = 0;
}
//结束拖拽时开始计时
if (Input.GetMouseButtonUp(0))
{
isTime = true;
}
if (isTime)
{
noOperate += Time.deltaTime;
if (noOperate >= 10)
{
isTime = false;
//超过一定时间开始自动播放
StartCoroutine("onAutoRotate");
}
}
}
}
//开启自动播放
private IEnumerator onAutoRotate()
{
while (true)
{
for (int i = index; i < sprit_arr.Length; i++)
{
image.sprite = sprit_arr[i];
index++;
yield return new WaitForSeconds(1 / 30.0f);
}
index = 0;
}
}
}