Unity 게임 카드 스크롤 효과 구현

23914 단어 Unity카드 스크롤
최근 프로젝트 의 이벤트 패 널 은 카드 미리 보기 효 과 를 반복 해 야 하 는데,자신 이 쓰 면 쓸 수 있 을 것 같 지만 시간 이 걸 릴 수 있 습 니 다.Github 에 오픈 소스 가 있 는 프로젝트 를 보고 빌려 썼 습 니 다.Github 의자원 주소작가 님 의 공유 에 감 사 드 립 니 다.
이 블 로 그 는 여러분 에 게 이 플러그 인 을 어떻게 이용 하 는 지 알려 주 는 데 목적 을 두 고 있 습 니 다.
플러그 인의 핵심 은 프로젝트 의 6 개의 스 크 립 트 입 니 다.다음은 6 개의 스 크 립 트 의 원본 코드 입 니 다.
DragEnhanceView.cs

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
 
public class UGUIEnhanceItem : EnhanceItem
{
 private Button uButton;
 private Image image;
 
 protected override void OnStart()
 {
 image = GetComponent<Image>();
 uButton = GetComponent<Button>();
 uButton.onClick.AddListener(OnClickUGUIButton);
 }
 
 private void OnClickUGUIButton()
 {
 OnClickEnhanceItem();
 }
 
 // Set the item "depth" 2d or 3d
 protected override void SetItemDepth(float depthCurveValue, int depthFactor, float itemCount)
 {
 int newDepth = (int)(depthCurveValue * itemCount);
 this.transform.SetSiblingIndex(newDepth);
 }
 
 public override void SetSelectState(bool isCenter)
 {
 if (image == null)
 image = GetComponent<Image>();
 image.color = isCenter ? Color.white : Color.gray;
 }
}
EnhanceScrollViewDragController.cs

using UnityEngine;
using System.Collections;
 
public class EnhanceScrollViewDragController : MonoBehaviour
{
 private Vector2 lastPosition = Vector2.zero;
 private Vector2 cachedPosition = Vector2.zero;
 private GameObject dragTarget;
 
 private Camera targetCamera;
 private int rayCastMask = 0;
 private bool dragStart = false;
 
 public void SetTargetCameraAndMask(Camera camera, int mask)
 {
 this.targetCamera = camera;
 this.rayCastMask = mask;
 }
 
 void Update()
 {
 if (this.targetCamera == null)
 return;
#if UNITY_EDITOR
 ProcessMouseInput();
#elif UNITY_IOS || UNITY_ANDROID
 ProcessTouchInput();
#endif
 }
 
 /// <summary>
 /// Process Mouse Input
 /// </summary>
 private void ProcessMouseInput()
 {
 if (Input.GetMouseButtonDown(0))
 {
 if (targetCamera == null)
 return;
 dragTarget = RayCast(this.targetCamera, Input.mousePosition);
 lastPosition.x = Input.mousePosition.x;
 lastPosition.y = Input.mousePosition.y;
 }
 if (Input.GetMouseButton(0))
 {
 if (dragTarget == null)
 return;
 cachedPosition.x = Input.mousePosition.x;
 cachedPosition.y = Input.mousePosition.y;
 Vector2 delta = cachedPosition - lastPosition;
 if (!dragStart && delta.sqrMagnitude != 0f)
 dragStart = true;
 
 if (dragStart)
 {
 // Notify target
 dragTarget.SendMessage("OnEnhanceViewDrag", delta, SendMessageOptions.DontRequireReceiver);
 }
 lastPosition = cachedPosition;
 }
 
 if (Input.GetMouseButtonUp(0))
 {
 if (dragTarget != null && dragStart)
 {
 dragTarget.SendMessage("OnEnhaneViewDragEnd", SendMessageOptions.DontRequireReceiver);
 }
 dragTarget = null;
 dragStart = false;
 }
 }
 
 /// <summary>
 /// Process Touch input
 /// </summary>
 private void ProcessTouchInput()
 {
 if (Input.touchCount > 0)
 {
 Touch touch = Input.GetTouch(0);
 if (touch.phase == TouchPhase.Began)
 {
 if (targetCamera == null)
 return;
 dragTarget = RayCast(this.targetCamera, Input.mousePosition);
 }
 else if (touch.phase == TouchPhase.Moved)
 {
 if (dragTarget == null)
 return;
 if (!dragStart && touch.deltaPosition.sqrMagnitude != 0f)
 {
 dragStart = true;
 }
 if (dragStart)
 {
 // Notify target
 dragTarget.SendMessage("OnEnhanceViewDrag", touch.deltaPosition, SendMessageOptions.DontRequireReceiver);
 }
 }
 else if (touch.phase == TouchPhase.Ended)
 {
 if (dragTarget != null && dragStart)
 {
 dragTarget.SendMessage("OnEnhaneViewDragEnd", SendMessageOptions.DontRequireReceiver);
 }
 dragTarget = null;
 dragStart = false;
 }
 }
 }
 
 public GameObject RayCast(Camera cam, Vector3 inPos)
 {
 Vector3 pos = cam.ScreenToViewportPoint(inPos);
 if (float.IsNaN(pos.x) || float.IsNaN(pos.y))
 return null;
 if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) return null;
 
 Ray ray = cam.ScreenPointToRay(inPos);
 float dis = 100f;
 RaycastHit[] hits = Physics.RaycastAll(ray, dis, rayCastMask);
 if (hits.Length > 0)
 {
 for (int i = 0; i < hits.Length; i++)
 {
 GameObject go = hits[i].collider.gameObject;
 DragEnhanceView dragView = go.GetComponent<DragEnhanceView>();
 if (dragView == null)
 continue;
 else
 {
 // just return current hover object our drag target
 return go;
 }
 }
 }
 return null;
 }
}
EnhanceItem.cs

using UnityEngine;
using System.Collections;
 
public class EnhanceItem : MonoBehaviour
{
 // Start index
 private int curveOffSetIndex = 0;
 public int CurveOffSetIndex
 {
 get { return this.curveOffSetIndex; }
 set { this.curveOffSetIndex = value; }
 }
 
 // Runtime real index(Be calculated in runtime)
 private int curRealIndex = 0;
 public int RealIndex
 {
 get { return this.curRealIndex; }
 set { this.curRealIndex = value; }
 }
 
 // Curve center offset 
 private float dCurveCenterOffset = 0.0f;
 public float CenterOffSet
 {
 get { return this.dCurveCenterOffset; }
 set { dCurveCenterOffset = value; }
 }
 private Transform mTrs;
 
 void Awake()
 {
 mTrs = this.transform;
 OnAwake();
 }
 
 void Start()
 {
 OnStart();
 }
 
 // Update Item's status
 // 1. position
 // 2. scale
 // 3. "depth" is 2D or z Position in 3D to set the front and back item
 public void UpdateScrollViewItems(
 float xValue,
 float depthCurveValue,
 int depthFactor,
 float itemCount,
 float yValue,
 float scaleValue)
 {
 Vector3 targetPos = Vector3.one;
 Vector3 targetScale = Vector3.one;
 // position
 targetPos.x = xValue;
 targetPos.y = yValue;
 mTrs.localPosition = targetPos;
 
 // Set the "depth" of item
 // targetPos.z = depthValue;
 SetItemDepth(depthCurveValue, depthFactor, itemCount);
 // scale
 targetScale.x = targetScale.y = scaleValue;
 mTrs.localScale = targetScale;
 }
 
 protected virtual void OnClickEnhanceItem()
 {
 EnhanceScrollView.GetInstance.SetHorizontalTargetItemIndex(this);
 }
 
 protected virtual void OnStart()
 {
 }
 
 protected virtual void OnAwake()
 {
 }
 
 protected virtual void SetItemDepth(float depthCurveValue, int depthFactor, float itemCount)
 {
 }
 
 // Set the item center state
 public virtual void SetSelectState(bool isCenter)
 {
 }
}
EnhanceScrollView.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class EnhanceScrollView : MonoBehaviour
{
 public enum InputSystemType
 {
 NGUIAndWorldInput, // use EnhanceScrollViewDragController.cs to get the input(keyboard and touch)
 UGUIInput, // use UDragEnhanceView for each item to get drag event
 }
 
 // Input system type(NGUI or 3d world, UGUI)
 public InputSystemType inputType = InputSystemType.NGUIAndWorldInput;
 // Control the item's scale curve
 public AnimationCurve scaleCurve;
 // Control the position curve
 public AnimationCurve positionCurve;
 // Control the "depth"'s curve(In 3d version just the Z value, in 2D UI you can use the depth(NGUI))
 // NOTE:
 // 1. In NGUI set the widget's depth may cause performance problem
 // 2. If you use 3D UI just set the Item's Z position
 public AnimationCurve depthCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(0.5f, 1), new Keyframe(1, 0));
 // The start center index
 [Tooltip("The Start center index")]
 public int startCenterIndex = 0;
 // Offset width between item
 public float cellWidth = 10f;
 private float totalHorizontalWidth = 500.0f;
 // vertical fixed position value 
 public float yFixedPositionValue = 46.0f;
 
 // Lerp duration
 public float lerpDuration = 0.2f;
 private float mCurrentDuration = 0.0f;
 private int mCenterIndex = 0;
 public bool enableLerpTween = true;
 
 // center and preCentered item
 private EnhanceItem curCenterItem;
 private EnhanceItem preCenterItem;
 
 // if we can change the target item
 private bool canChangeItem = true;
 private float dFactor = 0.2f;
 
 // originHorizontalValue Lerp to horizontalTargetValue
 private float originHorizontalValue = 0.1f;
 public float curHorizontalValue = 0.5f;
 
 // "depth" factor (2d widget depth or 3d Z value)
 private int depthFactor = 5;
 
 // Drag enhance scroll view
 [Tooltip("Camera for drag ray cast")]
 public Camera sourceCamera;
 private EnhanceScrollViewDragController dragController;
 
 public void EnableDrag(bool isEnabled)
 {
 if (isEnabled)
 {
 if (inputType == InputSystemType.NGUIAndWorldInput)
 {
 if (sourceCamera == null)
 {
 Debug.LogError("## Source Camera for drag scroll view is null ##");
 return;
 }
 
 if (dragController == null)
 dragController = gameObject.AddComponent<EnhanceScrollViewDragController>();
 dragController.enabled = true;
 // set the camera and mask
 dragController.SetTargetCameraAndMask(sourceCamera, (1 << LayerMask.NameToLayer("UI")));
 }
 }
 else
 {
 if (dragController != null)
 dragController.enabled = false;
 }
 }
 
 // targets enhance item in scroll view
 public List<EnhanceItem> listEnhanceItems;
 // sort to get right index
 private List<EnhanceItem> listSortedItems = new List<EnhanceItem>();
 
 private static EnhanceScrollView instance;
 public static EnhanceScrollView GetInstance
 {
 get { return instance; }
 }
 
 void Awake()
 {
 instance = this;
 }
 
 void Start()
 {
 canChangeItem = true;
 int count = listEnhanceItems.Count;
 dFactor = (Mathf.RoundToInt((1f / count) * 10000f)) * 0.0001f;
 mCenterIndex = count / 2;
 if (count % 2 == 0)
 mCenterIndex = count / 2 - 1;
 int index = 0;
 for (int i = count - 1; i >= 0; i--)
 {
 listEnhanceItems[i].CurveOffSetIndex = i;
 listEnhanceItems[i].CenterOffSet = dFactor * (mCenterIndex - index);
 listEnhanceItems[i].SetSelectState(false);
 GameObject obj = listEnhanceItems[i].gameObject;
 
 if (inputType == InputSystemType.NGUIAndWorldInput)
 {
 DragEnhanceView script = obj.GetComponent<DragEnhanceView>();
 if (script != null)
 script.SetScrollView(this);
 }
 else
 {
 UDragEnhanceView script = obj.GetComponent<UDragEnhanceView>();
 if (script != null)
 script.SetScrollView(this);
 }
 index++;
 }
 
 // set the center item with startCenterIndex
 if (startCenterIndex < 0 || startCenterIndex >= count)
 {
 Debug.LogError("## startCenterIndex < 0 || startCenterIndex >= listEnhanceItems.Count out of index ##");
 startCenterIndex = mCenterIndex;
 }
 
 // sorted items
 listSortedItems = new List<EnhanceItem>(listEnhanceItems.ToArray());
 totalHorizontalWidth = cellWidth * count;
 curCenterItem = listEnhanceItems[startCenterIndex];
 curHorizontalValue = 0.5f - curCenterItem.CenterOffSet;
 LerpTweenToTarget(0f, curHorizontalValue, false);
 
 // 
 // enable the drag actions
 // 
 EnableDrag(true);
 }
 
 private void LerpTweenToTarget(float originValue, float targetValue, bool needTween = false)
 {
 if (!needTween)
 {
 SortEnhanceItem();
 originHorizontalValue = targetValue;
 UpdateEnhanceScrollView(targetValue);
 this.OnTweenOver();
 }
 else
 {
 originHorizontalValue = originValue;
 curHorizontalValue = targetValue;
 mCurrentDuration = 0.0f;
 }
 enableLerpTween = needTween;
 }
 
 public void DisableLerpTween()
 {
 this.enableLerpTween = false;
 }
 
 /// 
 /// Update EnhanceItem state with curve fTime value
 /// 
 public void UpdateEnhanceScrollView(float fValue)
 {
 for (int i = 0; i < listEnhanceItems.Count; i++)
 {
 EnhanceItem itemScript = listEnhanceItems[i];
 float xValue = GetXPosValue(fValue, itemScript.CenterOffSet);
 float scaleValue = GetScaleValue(fValue, itemScript.CenterOffSet);
 float depthCurveValue = depthCurve.Evaluate(fValue + itemScript.CenterOffSet);
 itemScript.UpdateScrollViewItems(xValue, depthCurveValue, depthFactor, listEnhanceItems.Count, yFixedPositionValue, scaleValue);
 }
 }
 
 void Update()
 {
 if (enableLerpTween)
 TweenViewToTarget();
 }
 
 private void TweenViewToTarget()
 {
 mCurrentDuration += Time.deltaTime;
 if (mCurrentDuration > lerpDuration)
 mCurrentDuration = lerpDuration;
 
 float percent = mCurrentDuration / lerpDuration;
 float value = Mathf.Lerp(originHorizontalValue, curHorizontalValue, percent);
 UpdateEnhanceScrollView(value);
 if (mCurrentDuration >= lerpDuration)
 {
 canChangeItem = true;
 enableLerpTween = false;
 OnTweenOver();
 }
 }
 
 private void OnTweenOver()
 {
 if (preCenterItem != null)
 preCenterItem.SetSelectState(false);
 if (curCenterItem != null)
 curCenterItem.SetSelectState(true);
 }
 
 // Get the evaluate value to set item's scale
 private float GetScaleValue(float sliderValue, float added)
 {
 float scaleValue = scaleCurve.Evaluate(sliderValue + added);
 return scaleValue;
 }
 
 // Get the X value set the Item's position
 private float GetXPosValue(float sliderValue, float added)
 {
 float evaluateValue = positionCurve.Evaluate(sliderValue + added) * totalHorizontalWidth;
 return evaluateValue;
 }
 
 private int GetMoveCurveFactorCount(EnhanceItem preCenterItem, EnhanceItem newCenterItem)
 {
 SortEnhanceItem();
 int factorCount = Mathf.Abs(newCenterItem.RealIndex) - Mathf.Abs(preCenterItem.RealIndex);
 return Mathf.Abs(factorCount);
 }
 
 // sort item with X so we can know how much distance we need to move the timeLine(curve time line)
 static public int SortPosition(EnhanceItem a, EnhanceItem b) { return a.transform.localPosition.x.CompareTo(b.transform.localPosition.x); }
 private void SortEnhanceItem()
 {
 listSortedItems.Sort(SortPosition);
 for (int i = listSortedItems.Count - 1; i >= 0; i--)
 listSortedItems[i].RealIndex = i;
 }
 
 public void SetHorizontalTargetItemIndex(EnhanceItem selectItem)
 {
 if (!canChangeItem)
 return;
 
 if (curCenterItem == selectItem)
 return;
 
 canChangeItem = false;
 preCenterItem = curCenterItem;
 curCenterItem = selectItem;
 
 // calculate the direction of moving
 float centerXValue = positionCurve.Evaluate(0.5f) * totalHorizontalWidth;
 bool isRight = false;
 if (selectItem.transform.localPosition.x > centerXValue)
 isRight = true;
 
 // calculate the offset * dFactor
 int moveIndexCount = GetMoveCurveFactorCount(preCenterItem, selectItem);
 float dvalue = 0.0f;
 if (isRight)
 {
 dvalue = -dFactor * moveIndexCount;
 }
 else
 {
 dvalue = dFactor * moveIndexCount;
 }
 float originValue = curHorizontalValue;
 LerpTweenToTarget(originValue, curHorizontalValue + dvalue, true);
 }
 
 // Click the right button to select the next item.
 public void OnBtnRightClick()
 {
 if (!canChangeItem)
 return;
 int targetIndex = curCenterItem.CurveOffSetIndex + 1;
 if (targetIndex > listEnhanceItems.Count - 1)
 targetIndex = 0;
 SetHorizontalTargetItemIndex(listEnhanceItems[targetIndex]);
 }
 
 // Click the left button the select next next item.
 public void OnBtnLeftClick()
 {
 if (!canChangeItem)
 return;
 int targetIndex = curCenterItem.CurveOffSetIndex - 1;
 if (targetIndex < 0)
 targetIndex = listEnhanceItems.Count - 1;
 SetHorizontalTargetItemIndex(listEnhanceItems[targetIndex]);
 }
 
 public float factor = 0.001f;
 // On Drag Move
 public void OnDragEnhanceViewMove(Vector2 delta)
 {
 // In developing
 if (Mathf.Abs(delta.x) > 0.0f)
 {
 curHorizontalValue += delta.x * factor;
 LerpTweenToTarget(0.0f, curHorizontalValue, false);
 }
 }
 
 // On Drag End
 public void OnDragEnhanceViewEnd()
 {
 // find closed item to be centered
 int closestIndex = 0;
 float value = (curHorizontalValue - (int)curHorizontalValue);
 float min = float.MaxValue;
 float tmp = 0.5f * (curHorizontalValue < 0 ? -1 : 1);
 for (int i = 0; i < listEnhanceItems.Count; i++)
 {
 float dis = Mathf.Abs(Mathf.Abs(value) - Mathf.Abs((tmp - listEnhanceItems[i].CenterOffSet)));
 if (dis < min)
 {
 closestIndex = i;
 min = dis;
 }
 }
 originHorizontalValue = curHorizontalValue;
 float target = ((int)curHorizontalValue + (tmp - listEnhanceItems[closestIndex].CenterOffSet));
 preCenterItem = curCenterItem;
 curCenterItem = listEnhanceItems[closestIndex];
 LerpTweenToTarget(originHorizontalValue, target, true);
 canChangeItem = false;
 }
}
NGUIEnhanceItem.cs

using UnityEngine;
using System.Collections;
 
/// <summary>
/// NGUI Enhance item example
/// </summary>
public class NGUIEnhanceItem : EnhanceItem
{
 private UITexture mTexture;
 
 protected override void OnAwake()
 {
 this.mTexture = GetComponent<UITexture>();
 UIEventListener.Get(this.gameObject).onClick = OnClickNGUIItem;
 }
 
 private void OnClickNGUIItem(GameObject obj)
 {
 this.OnClickEnhanceItem();
 }
 
 // Set the item "depth" 2d or 3d
 protected override void SetItemDepth(float depthCurveValue, int depthFactor, float itemCount)
 {
 if (mTexture.depth != (int)Mathf.Abs(depthCurveValue * depthFactor))
 mTexture.depth = (int)Mathf.Abs(depthCurveValue * depthFactor);
 }
 
 // Item is centered
 public override void SetSelectState(bool isCenter)
 {
 if (mTexture == null)
 mTexture = this.GetComponent<UITexture>();
 if (mTexture != null)
 mTexture.color = isCenter ? Color.white : Color.gray;
 }
 
 protected override void OnClickEnhanceItem()
 {
 // item was clicked
 base.OnClickEnhanceItem();
 }
}
UGUIEnhanceItem.cs

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
 
public class UGUIEnhanceItem : EnhanceItem
{
 private Button uButton;
 private Image image;
 
 protected override void OnStart()
 {
 image = GetComponent<Image>();
 uButton = GetComponent<Button>();
 uButton.onClick.AddListener(OnClickUGUIButton);
 }
 
 private void OnClickUGUIButton()
 {
 OnClickEnhanceItem();
 }
 
 // Set the item "depth" 2d or 3d
 protected override void SetItemDepth(float depthCurveValue, int depthFactor, float itemCount)
 {
 int newDepth = (int)(depthCurveValue * itemCount);
 this.transform.SetSiblingIndex(newDepth);
 }
 
 public override void SetSelectState(bool isCenter)
 {
 if (image == null)
 image = GetComponent<Image>();
 image.color = isCenter ? Color.white : Color.gray;
 }
}
위의 6 개의 스 크 립 트 를 가 져 온 후에 우 리 는 효 과 를 만 들 기 시 작 했 습 니 다.먼저 NGUI 부터 시작 합 니 다.우 리 는 장면 에 배경 을 마음대로 추가 한 다음 에 UIRoot 아래 에 빈 물 체 를 추가 하고 Scrollview 라 는 이름 을 붙 이 며 Enhance Scrollview.cs 스 크 립 트 를 추가 한 다음 에 6 개의 Texture 를 Scrollview 의 하위 물체 로 만 들 고 DragEnhance View.cs 스 크 립 트,NGUIEnhance Item.cs 스 크 립 트 를 추가 합 니 다.BoxCollider 구성 요소.이 어 우 리 는 여섯 개의 그림 아래 에 버튼 두 개 를 추가 하여 카드 를 좌우 로 전환 하 는 버튼 으로 이벤트 에서 Scrollview 를 끌 어 다 놓 고 각각 OnBtnLeft Click,OnBtnRightClick 방법 을 추가 합 니 다.이상 의 조작 을 한 후에 장면 은 대략 이렇다.

이 어 스크롤 뷰 를 선택 하여 스 크 립 트 인 자 를 조정 합 니 다.

ScaleCurve 이미지 매개 변 수 는 다음 과 같이 설정 되 어 있 으 며 좌우 순환 은 모두 pingpong 입 니 다.

Position Curve 이미지 매개 변 수 는 다음 과 같 습 니 다.좌우 순환 은 모두 loop 입 니 다.

DepthCurve 이미지 매개 변 수 는 다음 과 같 습 니 다.좌우 순환 은 모두 loop 입 니 다.

그리고 Scrollview 의 하위 물 체 를 ListEnhance Items 라 는 공개 배열 로 끌 어 다 놓 습 니 다.

이렇게 해서 우 리 는 설정 작업 을 모두 끝내 고 게임 을 실행 합 니 다.

효과 가 좋 은 것 을 볼 수 있 습 니 다.좌우 로 미 끄 러 지 거나 전환 단 추 를 누 르 면 카드 를 전환 하 는 기능 을 할 수 있 습 니 다.
이 어 UGUI 구현 을 살 펴 보 겠 습 니 다.UGUI 의 UI 레이아웃 은 기본적으로 NGUI 와 일치 합 니 다.다른 것 은 Scrollview 의 하위 물체 에 추 가 된 스 크 립 트 가 다 릅 니 다.필요 한 스 크 립 트 와 구성 요 소 는 다음 그림 과 같 습 니 다.

그리고 주의해 야 할 것 은 Scrollview 의 매개 변수 설정 에서 Input Type 이라는 속성 을 UGUI Input 으로 조정 해 야 한 다 는 것 입 니 다.

곡선 설정 과 하위 물체 배열 설정 은 NGUI 와 마찬가지 로 중복 되 지 않 습 니 다.이 동작 을 설정 한 후에 실행 하면 UGUI 도 똑 같은 카드 스크롤 효 과 를 실현 할 수 있 습 니 다.

지금까지 Github 에 게 감 사 드 립 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기