Unity使用ScrollRect制作摇杆(UGUI)

一. 前言

游戏开发中,摇杆功能是很常见的,Unity的UGUI提供了ScrollRect组件,非常适合用来制作摇杆,效果如下:
在这里插入图片描述

二. 实现

1. 制作UI

如下,创建Rocker节点和center节点,分别为摇杆的背景图和摇杆的手柄图。
Rocker节点挂上Rocker脚本(代码见文章最后),并赋值Content对象。
设置MovementTypeElastic
在这里插入图片描述

2. 运行Unity进行测试

运行Unity即可测试摇杆功能。

3. Rocker脚本代码

using UnityEngine;
using UnityEngine.UI;

public class Rocker: 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;
		if (contentPostion.magnitude > mRadius)
		{
			contentPostion = contentPostion.normalized * mRadius;
			SetContentAnchoredPosition(contentPostion);
		}
		Debug.Log(contentPostion);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章