Unity--摇杆的制作

制作摇杆的方式右两种,第一直接手动制作,第二通过UGUI中的ScrollRect进行制作

方法一:使用第一种方式手动制作摇杆时,需要直接手动在画布上创建摇杆的背景和摇杆

随后创建一个脚本用来控制,其中需要实现三个接口(eventsystem在创建画布时自动引入了),IBeginDragHandler,IDragHandler,IEndDragHandler这三个接口分别对应开始拖拽回调函数,正在回调函数,拖拽结束回调函数,直接见代码(代码是挂在杆上的)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class 遥控杆: MonoBehaviour,IBeginDragHandler, IDragHandler, IEndDragHandler
{
    Vector2 startPos;
    public Vector2 tempPos;
    // public Rigidbody2D rigidbody2D1;
    public GameObject qq;
    public void OnBeginDrag(PointerEventData eventData)//开始拖拽回调函数
    {
       startPos= transform.position;
    }

    public void OnDrag(PointerEventData eventData)//正在拖拽回调函数
    {
        tempPos=eventData.position-startPos;
        //Vector2.ClampMagnitude会限制tempPos向量的长度,如果tempPos向量长度大于了200,那么tempPos就为200
        transform.position = Vector2.ClampMagnitude(tempPos, 200) + startPos;
    }

    public void OnEndDrag(PointerEventData eventData)//拖拽结束回调函数
    {
        tempPos=Vector2.zero;
        transform.position = startPos;
    }

    void Update()
    {
        Move();
    }
    public void Move()
    {
        Vector2 temp=qq.transform.localPosition;
        temp.x+= tempPos.normalized.x * 400.0f * Time.deltaTime;
        temp.y+= tempPos.normalized.y * 400.0f * Time.deltaTime;
        qq.transform.localPosition = temp;
    }
}

 实现效果

第二种方法:使用UGUI自带的ScrollRect,使用的原理和方法一类似,区别就在于不需要自己在代码写杆跟随鼠标移动的代码,因为在ScrollRect中,点击content不松就会产生content跟随鼠标的效果,这里是需要限制一下范围即可,参考代码

using UnityEngine;
using UnityEngine.UI;

public class Rocker: ScrollRect
{
	protected float Radius = 0f;
    Vector2 contentPostion;//这是杆的position(因为使用了ScrollRect,所以就不用
                           //-startposotion,-startposotion为0,因此可以直接归一化后乘速
                           //度)
	protected  override  void Start()
	{
        base.Start();
        mRadius = content.sizeDelta.x * 0.5f;
	}

	public override void OnDrag(PointerEventData eventData)
	{
		base.OnDrag(eventData);
		contentPostion = content.anchoredPosition;
        //判断摇杆的位置是否大于半径
		if (contentPostion.magnitude > Radius)
		{
			contentPostion = contentPostion.normalized * mRadius;
            //这是直接设置content的api
			SetContentAnchoredPosition(contentPostion);
		}
	}
    public override void OnDEndrag(PointerEventData eventData)
	{
		base.OnEndDrag(eventData);
		SetContentAnchoredPosition(Vector2.Zero);//拖拽结束时,就把content的位置设置为0即可
        contentPostion=Vector2.Zero;
	}
    //控制物体的位移脚本和方法一差不多,因此就省略了
}

猜你喜欢

转载自blog.csdn.net/qq_62947569/article/details/131033867