Unity之使用ScrollRect制作游戏摇杆

Unity之使用ScrollRect制作游戏摇杆_第1张图片

using UnityEngine;
using UnityEngine.UI;
 
public class Script_05_05 :ScrollRect
{
	protected float mRadius=0f;

	protected override void Start()
	{
		base.Start();
		//计算摇杆块的半径
		mRadius = (transform as RectTransform).sizeDelta.x * 0.5f;
	}

	public override void OnDrag (UnityEngine.EventSystems.PointerEventData eventData)
	{
		base.OnDrag (eventData);
		var contentPostion = this.content.anchoredPosition;

        //contentPostion.magnitude 计算滑动摇杆的长度,需要让摇杆保持在圆形区域内
        if (contentPostion.magnitude > mRadius){
			contentPostion = contentPostion.normalized * mRadius; //contentPostion.normalized表示摇杆的单位向量,contentPostion:最终位置
            SetContentAnchoredPosition(contentPostion);
		}
	}
}

你可能感兴趣的:(Unity3D)