简体   繁体   English

Unity:根据向前的水平方向移动相机,而无需更改y位置

[英]Unity: Move camera based on forward horiz direction without changing y position

I'm creating a Google Cardboard VR app in Unity. 我正在Unity中创建一个Google Cardboard VR应用程序。 I want the camera to constantly move forwards horizontally in the direction the camera is facing but not change its Y position, ie not rise or fall. 我希望相机不断朝着相机所面对的方向水平向前移动,但不要改变其Y位置,即不要上升或下降。

I've managed to get it so that the camera moves forwards in whichever direction it's looking but can go up and down if you look that way, using this line of code: 我设法做到了这一点,以使相机可以朝着它所看的任何方向前进,但是如果您以这种方式看,则可以使用下面的代码行进上下:

transform.position = transform.position + cam.transform.forward * WalkingSpeed * Time.deltaTime;

Is there a simple way of fixing the Y axis, so that I get the behaviour I'm looking for? 是否有固定Y轴的简单方法,以便获得所需的行为? Here's the full code so far: 这是到目前为止的完整代码:

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

Note: ticking the 'freeze position' y value in rigidbody constraints doesn't work. 注意:在刚体约束中勾选“冻结位置” y值不起作用。

Many thanks in advance. 提前谢谢了。

You can try and split the forward vector up and build a new one where the y axis does not change: 您可以尝试分解正向矢量并构建一个新的矢量,其中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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM