Unity:在不改变 y 位置的情况下根据前向水平方向移动相机
Unity: Move camera based on forward horiz direction without changing y position
我正在 Unity 中创建一个 Google Cardboard VR 应用程序。我希望相机在相机面对的方向上不断水平向前移动但不改变其 Y 位置,即不上升或下降。
我已经设法让相机向前移动到它正在看的任何方向,但如果你朝那个方向看,可以上下移动,使用这行代码:
transform.position = transform.position + cam.transform.forward * WalkingSpeed * Time.deltaTime;
是否有一种简单的方法来固定 Y 轴,以便获得我正在寻找的行为?到目前为止,这是完整的代码:
using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour {
public float WalkingSpeed = 1.0f;
public bool WalkEnabled = true;
GameObject cam;
void Start () {
// This is the part of the Cardboard camera where I'm getting
// the forward position from:
cam = GameObject.FindWithTag("CCHead");
}
void Update ()
{
if (WalkEnabled)
{
walk();
}
}
void walk()
{
transform.localPosition = transform.localPosition + cam.transform.forward * WalkingSpeed * Time.deltaTime;
}
}
注意:在刚体约束中勾选 'freeze position' y 值不起作用。
非常感谢。
您可以尝试拆分前向矢量并构建一个 y 轴不变的新矢量:
transform.position =
transform.position +
new Vector3(
cam.transform.forward.x * WalkingSpeed * Time.deltaTime,
0, // add 0 to keep the y coordinate the same
cam.transform.forward.z * WalkingSpeed * Time.deltaTime);
我正在 Unity 中创建一个 Google Cardboard VR 应用程序。我希望相机在相机面对的方向上不断水平向前移动但不改变其 Y 位置,即不上升或下降。
我已经设法让相机向前移动到它正在看的任何方向,但如果你朝那个方向看,可以上下移动,使用这行代码:
transform.position = transform.position + cam.transform.forward * WalkingSpeed * Time.deltaTime;
是否有一种简单的方法来固定 Y 轴,以便获得我正在寻找的行为?到目前为止,这是完整的代码:
using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour {
public float WalkingSpeed = 1.0f;
public bool WalkEnabled = true;
GameObject cam;
void Start () {
// This is the part of the Cardboard camera where I'm getting
// the forward position from:
cam = GameObject.FindWithTag("CCHead");
}
void Update ()
{
if (WalkEnabled)
{
walk();
}
}
void walk()
{
transform.localPosition = transform.localPosition + cam.transform.forward * WalkingSpeed * Time.deltaTime;
}
}
注意:在刚体约束中勾选 'freeze position' y 值不起作用。
非常感谢。
您可以尝试拆分前向矢量并构建一个 y 轴不变的新矢量:
transform.position =
transform.position +
new Vector3(
cam.transform.forward.x * WalkingSpeed * Time.deltaTime,
0, // add 0 to keep the y coordinate the same
cam.transform.forward.z * WalkingSpeed * Time.deltaTime);