Unity Joystick Bug,它在第一次触摸时去同一个地方

Unity Joystick Bug, it goes to the same place on the firt touch

我正在尝试制作一个简单的球移动游戏,但有一个问题。当我按下操纵杆时,播放器会正确移动,但每次我触摸操纵杆时,它首先会进入 bottom-left 位置,而不是我刚刚单击的位置。即使我触摸另一个地方,屏幕中的位置也是它去的地方

这是操纵杆的脚本:

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

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{

private Image bgImg;
private Image joystickImg;
private Vector3 inputVector;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x / bgImg.rectTransform.sizeDelta.x);
        pos.y = (pos.y / bgImg.rectTransform.sizeDelta.x);

        inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
        inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

        // Move joystickImg
        joystickImg.rectTransform.anchoredPosition =
            new Vector3(inputVector.x * bgImg.rectTransform.sizeDelta.x / 3
                , inputVector.z * (bgImg.rectTransform.sizeDelta.y / 3));

    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    inputVector = Vector3.zero;
    joystickImg.rectTransform.anchoredPosition = Vector3.zero;
}

public float Horizontal()
{
    if (inputVector.x != 0)
        return inputVector.x;
    else
        return Input.GetAxis("Horizontal");
}

public float Vertical()
{
    if (inputVector.x != 0)
        return inputVector.z;
    else
        return Input.GetAxis("Vertical");
}
}

我注意到在 OnDrag() 中你使用 bgImg.rectTransform.sizeDelta.x 而不是 bgImg.rectTransform.sizeDelta.y 来设置 pos.y

并且在 Vertical() 中,您还检查 inputVector.x 而不是 inputVector.z

这些很可能不会修复错误,但它们是很好的修复。

有效的方法是删除

中的偏移量
inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);

将此更改为

inputVector = new Vector3(pos.x * 2, 0, pos.y * 2);

删除 +1 和 -1,应该可以解决问题![​​=19=]