![](/img/trans.png)
[英]How to make manual Scroll with scrolling according to the size of its contents in Unity?
[英]Scroll Rect manual scrolling through script Unity C#
我想為 Unity 制作一個 C# 腳本,使滾動視圖在按下“UP”鍵時向上滾動,並在按下“DOWN”鍵時向下滾動。
只需使用
ScrollRect.horizontalNormalizedPosition // value range (0 to 1)
要么
ScrollRect.verticalNormalizedPosition // value range (0 to 1)
嘗試在向上和向下按鈕的按鈕單擊事件處理程序上相應地lerp
這些值。
或者您可以在UnityUI-Extentions 中查看腳本HorizontalScrollSnap.cs
和VerticalScrollSnap.cs
希望這可以幫助
你的問題很不完整。 對於 2d 還是 3d? 你嘗試過什么?
繼承人如何做到這一點,有一些假設你遺漏了信息。 將此代碼添加到您的相機組件中:
void Update() {
if (Input.GetKeyDown(Input.KeyCode.W) {
transform.position = new Vector3(transform.position.x, transform.position.y + 2, transform.position.z);
}
}
這樣做是為了訪問將腳本附加到的對象變換,並在單擊 W 時使用 +2 調整其位置的 Y 值。
然后你可以添加更多的 if 語句並調整鍵,但核心就在那里。
為了平滑滾動(使用 lerp)。
[SerializeField]
private ScrollRect _scrollRectComponent;
[SerializeField]
RectTransform _container;
private IEnumerator LerpToPage(int page)
{
Vector2 _lerpTo = (Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - (Vector2)_scrollRectComponent.transform.InverseTransformPoint(target.position);
bool _lerp = true;
Canvas.ForceUpdateCanvases();
while(_lerp)
{
float decelerate = Mathf.Min(10f * Time.deltaTime, 1f);
_container.anchoredPosition = Vector2.Lerp(_scrollRectComponent.transform.InverseTransformPoint(_container.position), _lerpTo, decelerate);
if (Vector2.SqrMagnitude((Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - _lerpTo) < 0.25f)
{
_container.anchoredPosition = _lerpTo;
_lerp = false;
}
yield return null;
}
}
其他答案似乎不完整或過於復雜,所以我是這樣做的。 假設scroll
是你想要scroll
的方向, speed
是一個以內容單位/秒為單位控制你的滾動速度的屬性,並且scrollRect
是對 ScrollRect 組件的引用:
if (scroll != 0) {
float contentHeight = scrollRect.content.sizeDelta.y;
float contentShift = speed * scroll * Time.deltaTime;
scrollRect.verticalNormalizedPosition += contentShift / contentHeight;
}
這應該為任何內容大小移動適當的量,並正確地導致頂部和底部的彈性回彈(如果您的 ScrollRect 已為此配置)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.