How to make the object and the camera move together in Unity

When developing VR or AR applications in Unity, we want the object and the camera to follow and move. We need to obtain the parameters of the camera first, and then we need to modify the parameters of the object to make it follow the movement.  


public class TestCubeStability : MonoBehaviour
{
    public GameObject mainCamera;
    // Start is called before the first frame update
    void Start()
    {
        mainCamera = GameObject.Find("Main Camera");
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 Cam_Pos = mainCamera.transform.position;
        Vector3 Cam_forward = mainCamera.transform.forward;
        Vector3 Cam_right = mainCamera.transform.right;
        Vector3 Cam_up = mainCamera.transform.up.normalized;
        Vector3 OffSet = new Vector3(0, 1, 0);

        Debug.Log(Cam_Pos);

        this.transform.rotation = mainCamera.transform.rotation;
        this.transform.position = Cam_Pos + Cam_forward;
    }
}

Use this pointer to change the parameters of the object under this script, don’t forget to mount the script under the object, it can be executed automatically

Guess you like

Origin blog.csdn.net/Aaron9489/article/details/128117292