这篇文章主要为大家详细介绍了Unity实现简单摇杆的制作,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
利用UGUI制作一个简单摇杆,效果图
1、首先建立两个Image,然后将其中一个为父物体,另一个为子物体,并且调整好大小:
ps:将子物体的锚点设置为居中
2、在父物体上写个JoyStick.cs脚本:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class JoyStick : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler
{
public static float h, v; //传出hv
public float maxDis; //最大距离
private RectTransform childRectTrans;
private Coroutine coroutine = null;
void Start()
{
childRectTrans = transform.GetChild(0) as RectTransform;
}
public void OnBeginDrag(PointerEventData eventData)
{
if (coroutine != null)
{
StopCoroutine(coroutine);
coroutine = null;
}
}
public void OnDrag(PointerEventData eventData)
{
Vector3 outPos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(this.transform as RectTransform, eventData.position, eventData.pressEventCamera, out outPos))
{
childRectTrans.position = outPos;
//限制拖拽距离
childRectTrans.anchoredPosition = Vector2.ClampMagnitude(childRectTrans.anchoredPosition, maxDis);
//或者利用子物体和父物体的距离判断是否超过最大距离,当距离大于等于最大的距离时候,
//计算父物体和子物体的向量,然后利用向量*最大距离来限制拖拽距离
//if (Vector2.Distance(childRectTrans.position, this.transform.position) > maxDis)
//{
// Vector2 dir = (childRectTrans.position - this.transform.position).normalized;
// childRectTrans.anchoredPosition = dir * maxDis;
/
织梦狗教程
本文标题为:Unity实现简单摇杆的制作


基础教程推荐
猜你喜欢
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- 实例详解C#实现http不同方法的请求 2022-12-26
- Unity shader实现高斯模糊效果 2023-01-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#中的Linq to JSON操作详解 2023-06-08
- C# 解析XML和反序列化的示例 2023-04-14