简体   繁体   English

在 Unity 中使用脚本重置相机的问题

[英]Issues with camera reset using a script in Unity

I want to centre the camera on the object and then, if player clicks on button (which will be added later) or outside of the pop-up which will be triggered by clicking on object (camera movement is just a first step).我想将相机放在 object 上,然后,如果玩家点击按钮(稍后将添加)或在弹出窗口之外点击 object(相机移动只是第一步)。

My idea was to store the very first position of the camera and transform it back again if mouse is clicking outside of any clickable objects, but looks like it's not working.我的想法是存储相机的第一个 position 并在鼠标在任何可点击对象之外单击时再次将其转换回来,但看起来它不起作用。

void Update()
{
    Vector3 camoriginposition;
    if (Input.GetMouseButtonDown(0))
    {
        Camera cam = Camera.main;
        camoriginposition = Camera.main.transform.position;
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            Rigidbody rb;
            if (rb = hit.transform.GetComponent<Rigidbody>())
            {
                Vector3 obj = rb.transform.position - new Vector3(0, -3, 2);
                cam.transform.position = obj;
                Debug.Log("curr cam pos" + cam.transform.position);
            }
            else
            {
                cam.transform.position = camoriginposition;
                Debug.Log("It triggers!");
            }
        }
    }
}

I receive the Debug.Log output, but looks like transform.position cannot be processed.我收到 Debug.Log output,但看起来像 transform.position 无法处理。

Do you have any ideas how to fix it?您有任何解决方法的想法吗?

I'm not sure what behaviour you are meaning by "not working", but maybe It's because you are declaring camoriginposition on every Update() , which would be definitely not the desired behaviour.我不确定您所说的“不工作”是什么意思,但也许是因为您在每个Update()上都声明camoriginposition ,这绝对不是所需的行为。 Whenever you tries to store your cam's origin position to local variable, it will be gone when the Update() scope ends, and will be initialized again with new Update() call.每当您尝试将凸轮的原点 position 存储到局部变量时,当Update() scope 结束时它将消失,并且将使用新的Update()调用再次初始化。

You have to seperate camoriginposition from Update() , like:您必须将camoriginpositionUpdate()分开,例如:

private Vector3 camoriginposition;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
         ...
}

And, it seems like there are another problem.而且,似乎还有另一个问题。 You are storing camoriginposition on every mouse click, but with your description, It seems like it should be stored when the ray actually hits the gameobject.您在每次鼠标单击时都存储camoriginposition ,但是根据您的描述,它似乎应该在射线实际击中游戏对象时存储。

You should move camoriginposition = Camera.main.transform.position;你应该移动camoriginposition = Camera.main.transform.position;

into进入

if (rb = hit.transform.GetComponent<Rigidbody>()) block. if (rb = hit.transform.GetComponent<Rigidbody>())块。

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

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