之前做过一次但是忘了,这次费了老大劲,发誓一定长记性!
1. JoyStick摇杆在canvas画布中的绑定
- 在canvas中创建一个image命名为摇杆背景
- 再在这个背景下创建一个image命名为摇杆
- 创建JoyStick代码
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
private Image joystickBg;
private Image joystick;
private Vector3 inputVector;
void Start()
{
joystickBg = GetComponent<Image>();
joystick = transform.GetChild(0).GetComponent<Image>();
}
public virtual void OnDrag(PointerEventData eventData)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBg.rectTransform, eventData.position, eventData.pressEventCamera, out pos))
{
pos.x = (pos.x / joystickBg.rectTransform.sizeDelta.x);
pos.y = (pos.y / joystickBg.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2 - 1, pos.y * 2 - 1, 0);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
joystick.rectTransform.anchoredPosition = new Vector3(inputVector.x * (joystickBg.rectTransform.sizeDelta.x / 2), inputVector.y * (joystickBg.rectTransform.sizeDelta.y / 2));
}
}
public virtual void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public virtual void OnPointerUp(PointerEventData eventData)
{
inputVector = Vector3.zero;
joystick.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal()
{
return (-1)*inputVector.x;
}
public float Vertical()
{
return inputVector.y;
}
}
- 将JoyStick代码绑定在摇杆背景上,摇杆将可以围绕摇杆背景移动
2. 将摇杆绑定在角色身上实现移动
- 创建Player代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed = 5f;
public Joystick joystick; // 参考到摇杆脚本
void Update()
{
Vector3 moveVector = new Vector3(joystick.Horizontal(), joystick.Vertical(), 0f);
transform.Translate(moveVector * moveSpeed * Time.deltaTime);
}
}
- 将代码添加到角色身上,并将摇杆背景拖拽到右边的脚本上
这样就好了!
后续添加动画什么的即可自行设置。