Raycast打得不好用

时间:2016-06-13 05:47:43

标签: c# unity3d

我编写了一个代码,通过选择它来改变对象的颜色

void Update () {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
        if(Physics.Raycast(ray,out hit, 1000.0f) && Input.GetMouseButtonDown (0))
        {
            if(hit.collider.gameObject == this.gameObject)
            {
                Debug.Log("Wall Clicked");

                mgr.clickedWall=gameObject;

        }
        else if(Physics.Raycast(ray,out hit, 1000.0f) && Input.GetMouseButtonDown (1)) 
        {

            hit.collider.gameObject.renderer.material.color = Color.red;

        }
    }

当主相机处于初始位置但相机时,它可以正常工作 位置会更改颜色更改,但不会更改我单击的对象。这里的isuue是什么。

1 个答案:

答案 0 :(得分:1)

我觉得你的整个逻辑是错误的。祢的这样的事情。请注意,这是附在相机上,而不是你点击的游戏对象。我认为你的问题源于在一个if中检查是否鼠标按钮关闭的光线投射。

 void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.gameObject.tag == "Test")
                {
                    Debug.Log("Wall Clcked");
                }
            }

        }
        if (Input.GetMouseButtonDown(1))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                hit.collider.gameObject.GetComponent<Renderer>().material.color = Color.red;
            }

        }
    }
相关问题