1
votes

I want to hit a mesh with a raycast and get the mouse/screen coordinates of where the hit occurred.

public class GetCoordinates: MonoBehaviour {

    private GameObject _objectToHit;

    private RaycastHit hit;
    private Collider coll;
    private Ray ray;
    private float hitDistance = 200f;

    void Start()
    {
        coll = GetComponent<Collider>();
        _objectToHit = GameObject.Find("Street");
    }

    void Update()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (coll.Raycast(ray, out hit, hitDistance))
        {
              Debug.Log(hit.point);
        }
    }
}

Also I am not sure where to add the script, to the object being hit or to the camera?

1
I don't know where you got that script but it looks alright, why haven't you tried adding it to the object or the camera? (I know which one you should add it to, but I think you should try to figure it out for yourself, considering you already have the script) - EmilioPelaez
I'm voting to close this question as off-topic because this calls for an EXTREMELY BASIC TUTORIAL IN THE SUBJECT (note for example "I don't know where to put the script"), rather than an actual question-answer. There is no "answer" here other than a long tutorial. - Fattie
it's possible you're looking for RAYCASTALL. You can very easily find a HUGE number of QA and tutorials on this. - Fattie
hi @silentace, are you there? - Fattie

1 Answers

1
votes

You want to use Camera.WorldToScreenPoint to convert the world hit point position into screen position. Also you need to have only one instance of this script in your game otherwise you'll have several ray casts. You should consider this before choosing where to put this script. We can not help you to make this choice without more informations on what it is used for, on how many objects, etc.

EDIT about the script use:

One thing is certain: the ray cast script has to have a unique instance. If you want to interact with other objects through this script, you should use the GameObject.GetComponent function on hit.collider.gameobject in order to access the script that will do the what you want.

For example, if you have a gate on your street, clicking on it will call the toggleOpen() function contained in the GateBehaviour script on the Gate object like that :

if (coll.Raycast(ray, out hit, hitDistance))
{
    if(hit.collider.tag == "Gate")
    {
        GateBehaviour gate = hit.collider.gameobject.GetComponent<GateBehaviour>()
        if(gate)
            gate.toggleOpen();
    }
    Debug.Log(hit.point);
}

You should ideally have something like a class called Interractable that would offer a unique interface for all the interractable objects on the street. The street itself could also inherit from this interface.