尝试实现基于垂直轴和水平轴旋转对象的方法,该方法由光标在图像上的位置确定。
使用操纵杆为控件创建移动3D游戏。目的是使用操纵杆旋转。图像示例:https://imgur.com/a/hd9QiVe绿色圆圈随着用户按下而移动,并返回介于-1到1之间的X和Y值,其中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到垂直和水平到直接对象朝向角度都需要角度。目前使用的公式不提供任何角度。
如果你想获得Vector的角度,请使用Vector2.SignedAngle()
:
var inputAngle = Vector2.SignedAngle(Vector2.right, inputVector);
角度是相对的,这就是你需要指定Vector2.right
作为第一个参数的原因。还有一个Vector2.Angle()
方法,但它只返回两个角度之间的距离,并没有考虑方向。
如果您需要验证输入向量是否符合您的想法,请使用Debug.Log()
打印您的inputVector
。