Question

I have a camera looking down on my game world. I want to allow the user to click on objects. The following script is attached to the MainCamera.

void Update () {
    if (holdingSomething)
    {
        if (Input.GetMouseButtonUp(0))
        {
            holdingSomething = false;   
        }
    }
    else if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Vector3 mousePos = new Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
        Vector3 rayOrigin = new Vector3(Camera.main.ScreenToWorldPoint(mousePos).x,Camera.main.ScreenToWorldPoint(mousePos).y,Camera.main.transform.position.z);
        Vector3 rayDirection = new Vector3(Camera.main.transform.rotation.x,Camera.main.transform.rotation.y,Camera.main.transform.rotation.z);
        Debug.Log("Mouse button is down" + mousePos);
        Debug.Log("rayOrigin " + rayOrigin);
        Debug.Log("rayDirection " + rayDirection);
        Ray ray = new Ray(rayOrigin,rayDirection);
        if (Physics.Raycast(ray, out hit))
        {
            Debug.Log("We just touched " + hit.collider);
        }
    }
}

The line Debug.Log("We just touched " + hit.collider); is never called. I don't think my ray is being built right. Here is the output of the other debug messages. At each message they rayOrigin is the same, even though the mousePos changes.

Mouse button is down(418.7, 195.1, 0.0)
rayOrigin (0.0, 6.2, -7.3)
rayDirection (0.3, 0.0, 0.0)

Mouse button is down(417.7, 278.0, 0.0)
rayOrigin (0.0, 6.2, -7.3)
rayDirection (0.3, 0.0, 0.0)

So where am I going wrong?

Était-ce utile?

La solution

I would define your Ray like this:

Ray ray = Camera.Main.ScreenPointToRay(Input.mousePosition);

As for your code, I can't test your code right now so I don't know what exactly goes wrong. Because you should be able to do as you described, even though my answer is an easier alternative.

You can use Debug.DrawLine to draw a line of the raycast you use. Then, you can see what your raycast looks like in the debugger, during runtime. You can see then how your raycast is positioned. You'd be able to see the start and end point of the ray. If one of them is off, you can check your code while knowing which part is wrong.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top