【问题标题】:Get angle from Horizontal and Vertical Axis从水平轴和垂直轴获取角度
【发布时间】:2019-04-09 16:53:27
【问题描述】:

尝试实现基于图像上光标位置确定的垂直轴和水平轴统一旋转对象的方法。

使用操纵杆为移动设备创建 3D 游戏进行控制。目的是使用操纵杆旋转。 图片示例: https://imgur.com/a/hd9QiVe 绿色圆圈随着用户按下和返回而移动 X 和 Y 值介于 -1 到 1 之间,中间为 0。 只是为了可视化输入是如何发生的: https://imgur.com/a/8QVRrIh 如图所示,我只是想要一个角度或一种方法来在检测到用户输入的方向上移动对象。

尝试了几种使用 atan 和 tan 计算角度的方法,但我的数学很差,而且我不完全确定我首先获得了正确的值。

//背景摇杆指的是第一张图片中的白色圆圈

        pos.x = (pos.x / backgroundJoystick.rectTransform.sizeDelta.x);
        pos.y = (pos.y / backgroundJoystick.rectTransform.sizeDelta.y);
        inputVector = new Vector3(pos.x * 2f, 0, pos.y * 2f);
        inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;

//抓取轴输入

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

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

如代码中所示,从 input.getaxis 中需要垂直和水平以将对象指向角度。 目前使用的公式不提供任何角度。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    如果要获取 Vector 的角度,请使用 Vector2.SignedAngle():

    var inputAngle = Vector2.SignedAngle(Vector2.right, inputVector);
    

    角度是相对的,这就是为什么您需要指定Vector2.right 作为第一个参数。还有一个Vector2.Angle()方法,不过只是返回两个角度之间的距离,没有考虑方向。

    如果您需要验证输入向量是否与您认为的一样,请使用Debug.Log() 打印您的inputVector

    【讨论】:

    • 感谢这段代码解决了我的问题: var inputAngle = Vector2.SignedAngle(Vector2.right, pos);我改变的一件事是采用以前的 Vector2 而不是 Vector3 来获得我的角度,如下所示:reddit.com/r/Unity2D/comments/7irplq/…
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多