0
点赞
收藏
分享

微信扫一扫

【Unity】使用UGUI制作一个移动摇杆

晚安大世界 2022-01-20 阅读 46

UGUI移动摇杆


话不多说,直接上代码!

摇杆的代码:

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

public class Joy : MonoBehaviour
{
    //摇杆的位置
    public RectTransform imgJoy;
    //摇杆上的事件相关
    public EventTrigger et;
	//Player脚本
    public Player player;

    void Start()
    {
        //为摇杆注册事件
        //拖动中
        EventTrigger.Entry en = new EventTrigger.Entry();
        en.eventID = EventTriggerType.Drag;
        en.callback.AddListener(JoyDrag);
        et.triggers.Add(en);

        //结束拖动
        en = new EventTrigger.Entry();
        en.eventID = EventTriggerType.EndDrag;
        en.callback.AddListener(EndJoyDrag);
        et.triggers.Add(en);
    }

	//抬起
    private void JoyDrag(BaseEventData data)
    {
        PointerEventData eventData = data as PointerEventData;
        imgJoy.position += new Vector3(eventData.delta.x, eventData.delta.y, 0);

        //我们有专门的参数 得到相对于锚点的点
        //!这个60是基于图片大小测出来的,是用来限定摇杆移动范围的
        if(imgJoy.anchoredPosition.magnitude>60)
        {
            //拉回来
            //单位向量 乘以 长度 = 临界位置
            imgJoy.anchoredPosition = imgJoy.anchoredPosition.normalized * 60;
        }

        //让玩家移动
        player.Move(imgJoy.anchoredPosition);
    }

	//按下
    private void EndJoyDrag(BaseEventData data)
    {
        //回归中心点
        imgJoy.anchoredPosition = Vector2.zero;
        //停止移动 传0向量进去 即可
        player.Move(Vector2.zero);
    }
}

角色代码

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

public class Player : MonoBehaviour
{
    private Vector3 nowMoveDir = Vector3.zero;
    //移动速度
    public float moveSpeed = 10;
    //转向速度
    public float roundSpeed = 40;

    void Update()
    {
        if(nowMoveDir != Vector3.zero)
        {
            //朝面朝向移动
            this.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
            //不停的朝目标方向转向
            this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(nowMoveDir), roundSpeed * Time.deltaTime);
        }
    }

    public void Move(Vector2 dir)
    {
        nowMoveDir.x = dir.x;
        nowMoveDir.y = 0;
        nowMoveDir.z = dir.y;
    }

}

举报

相关推荐

0 条评论