简体   繁体   中英

Raycast hit dont work properly

I have written a code to change the color of a object by selecting it

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;

        }
    }

it works fine when main camera is on the initial position but when the camera position changes color changes but not on the object that I clicked.what is the isuue over here.

I feel like your whole logic is wrong. Thy out something like this. please note that this is attached to the camera and not the gameobject you are clicking. I think your problem stems from doing the raycast in a if that also checks if a mouse button is down.

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

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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