UGUI实现虚拟摇杆
程序员文章站
2024-03-24 11:16:58
...
给摇杆挂载的脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class mover : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
{
public RectTransform backrect;//需要在unity中将背景UI拖到里面
public RectTransform selfrect;//需要在unity中将摇杆UI拖到里面
public float radis;//摇杆半径
public Vector2 direction;//摇杆方向
public bool ismoving = false;
public Action<Vector2> MoveEvent;//作为人物移动事件的调用
public void Awake()
{
radis = backrect.sizeDelta.x / 2;
}
public void Update()
{
if (ismoving)
if (MoveEvent != null)
MoveEvent.Invoke(direction);
}
public void OnBeginDrag(PointerEventData eventData)
{
selfrect.anchoredPosition = eventData.position - backrect.anchoredPosition;
ismoving = true;
}
public void OnDrag(PointerEventData eventData)
{
selfrect.anchoredPosition = eventData.position - backrect.anchoredPosition;//计算摇杆正确位置
if ((backrect.position - selfrect.position).magnitude > radis)
selfrect.anchoredPosition = Vector2.ClampMagnitude(selfrect.anchoredPosition, radis);//限制摇杆范围
direction = selfrect.anchoredPosition.normalized;
}
public void OnEndDrag(PointerEventData eventData)
{
selfrect.anchoredPosition = Vector2.zero;
ismoving = false;
}
}
给unity中挂载的脚本:
给游戏对象挂载的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
public CharacterController controller ;
public mover VJ;
public float speed = 5;
private Vector3 Direction = Vector3.zero;
private void Awake()
{
VJ.MoveEvent = Move;//注册游戏对象的移动
}
private void Move(Vector2 direction)
{
Direction.x = direction.x;
Direction.z = direction.y;
transform.rotation = Quaternion.LookRotation(Direction);
controller.Move(transform.forward * speed * Time.deltaTime);
}
}
//需要在玩家对象上添加组件:charactre collkklion 然后拖给脚本中的charactercontroller
用法:
1.将第一个脚本挂载到UI摇杆image上
2.将第二个脚本挂载到unity任意模型上
3.将相应物体拖入到两个脚本中即可