Problem with raycast

Hi,

Just started learning about raycasting and I’m trying to setup a script that determines if I press different sprites and then tell me their names. The problem is that sometimes it registers the hit.collider and tells me the name, sometimes it don’t - and it can even be the same sprite not registering.

So I was thinking it might be the ray being weirdly thrown since I’m not so familiar with it. But I can’t seem to draw a Debug.Drawline. Could someone please help me?

[SerializeField]
GameObject last;
[SerializeField]
GameObject next;

void FixedUpdate () {
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 10;

        if (Input.GetMouseButtonDown(0))
            {

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);

                if (hit.collider == last)
                {
                    print(hit.collider.name);
            }
                if (hit.collider == next)
                {
                    print(hit.collider.name);
            }
}
}

I got the DrawLine working and it seems the ray is coming sideways. My game is 2D. How can I get the ray to go from the cursor and straight in a z direction from the cursors place?

I’d say something in this line:

Vector3 rayPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z);
Ray ray = new Ray(rayPosition, Vector3.back); // Towards negative z, use .forward for positive z

Though ScreenPointToRay should have also supported orthogonal camera’s.

Hm this does not work :/, now it doesn’t register any hit at all

I did some inbetween version and now it seems to hit correct. But sometimes it doesn’t fire a ray. How could that be? Every 5th or 6th ray doesn’t fire at all. I can see because those times there doesn’t appear a debug.drawline. Is this a common problem?

        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = 10;

        if (Input.GetMouseButtonDown(0))
            {
            //rayPos = Camera.main.ScreenPointToRay(Input.mousePosition);
            Ray ray = new Ray(mousePos, Vector3.back);
            RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
            Debug.DrawLine(ray.origin, ray.direction);
}

Found this: “Also, using GetMouseButtonDown in FixedUpdate does not work and should never be used, since *Down and *Up events are only true for the single frame in which they occur, which may or may not coincide with a physics frame.”

Ok so that might be the problem. Anyone else have any idea on how to go about this in another way? I mean, I don’t want it to send rays unless I press the sprite.

Put it in Update instead of FixedUpdate.

Yeah tried that, didn’t work. Thanks anyway :).

Have you checked the example in the manual?