In 100 lines, you can make a nice snapshot!
Are you ready? Okay, Go.
First, Script here!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ScScrollSnap : MonoBehaviour, IPointerUpHandler, IPointerDownHandler {
ScrollRect scrollRect;
Transform layout;
RectTransform layoutRect;
public List<Transform> imageList;
int imageCount;
public int index;
public float snapSpeed;
float touchStartPosX;
float touchEndPosX;
float tempPosX;
int ii;
void Awake ()
{
scrollRect = GetComponent<ScrollRect>();
layout = transform.Find("Layout");
layoutRect = layout.GetComponent<RectTransform>();
imageList = new List<Transform>();
ResetImageList();
}
void Update()
{
if (imageCount != layout.childCount)
ResetImageList();
}
public void OnPointerDown(PointerEventData eventData)
{
if (!scrollRect.enabled)
return;
touchStartPosX = layoutRect.anchoredPosition.x;
}
public void OnPointerUp(PointerEventData eventData)
{
if (layout.childCount == 0)
return;
touchEndPosX = layoutRect.anchoredPosition.x;
float distance = DistanceTouchPoint();
bool isSnap = distance > 50 ? true : false;
if (!isSnap)
{
StartCoroutine(Snap());
return;
}
StartCoroutine(SnapView());
}
IEnumerator SnapView()
{
if (touchStartPosX >= touchEndPosX)
index++;
else
index--;
index = Mathf.Clamp(index, 0, imageList.Count - 1);
yield return StartCoroutine(Snap());
}
IEnumerator Snap()
{
float time = 0;
scrollRect.enabled = false;
while(time <= 1)
{
time += Time.deltaTime * snapSpeed;
float tempPosX = Mathf.Lerp(layoutRect.anchoredPosition.x, -(imageList[index].GetComponent<RectTransform>().anchoredPosition.x), time);
layoutRect.anchoredPosition = new Vector2(tempPosX, layoutRect.anchoredPosition.y);
yield return null;
}
scrollRect.enabled = true;
}
void ResetImageList()
{
imageList.Clear();
for (ii = 0; ii < layout.childCount; ii++)
{
imageList.Add(layout.GetChild(ii));
}
imageCount = imageList.Count;
}
float DistanceTouchPoint()
{
float distance = Mathf.Abs(touchStartPosX - touchEndPosX);
return distance;
}
}
Second, Configure the UI like this!
Determine the width of the scroll area you want.
I'll scroll left and right.
Take a touch with ray cast and red is always right.
Put the script above and adjust the Snap Speed (If the Snap Speed is 0, it will not work)
Thank you!
Congratulations @bringiton0652! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit