【问题标题】:Unity Joystick Bug, it goes to the same place on the firt touchUnity Joystick Bug,第一次触摸它会去同一个地方
【发布时间】:2020-02-24 20:02:39
【问题描述】:

我正在尝试制作一个让球移动的简单游戏,但出现了问题。当我按下操纵杆时,玩家会正确移动,但每次我触摸操纵杆时,它都会首先进入左下角的位置,而不是我刚刚点击的位置。即使我触摸另一个地方,屏幕中的位置也是它的位置

这是操纵杆的脚本:

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");
}
}

【问题讨论】:

标签: c# unity3d joystick


【解决方案1】:

我注意到在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,应该可以解决它!

【讨论】:

  • 非常感谢,它对我来说很好,甚至感谢其他更正
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多