Know witch object I aim

Hello

I’ve display a little dot (•) on the center of my screen and I would detect which object is dotted by my dot.

For example, I want in this example get the Tree GameObject.

Can you help me?
Thank you

C:

public GameObject Camera; //Assign camera here

void Update () {
   RaycastHit hit;
   if (Physics.Raycast(Camera.transform.position, Camera.transform.forward, out hit, Mathf.Infinity)) {
      //here you can get the gameobject, by hit.collider.gameObject
   }

}
1 Like

That will shoot a ray from the camera forward, but it doesn’t guarantee that ray will be at the exact position of the dot. It is better to use something like this, where screenPoint is the position of the dot.

Ray rayFromCrosshairToWorld = Camera.main.ScreenPointToRay(screenPoint);
        if (Physics.Raycast(rayFromCrosshairToWorld, out hit))
        {
            //do stuff
        }

Also you can change your raycast to have a length argument so that you aren’t hitting trees a million miles away which you probably don’t want:

Physics.Raycast(rayFromCrosshairToWorld, out hit, 10.0f)

If the dot’s in the center, and most of the crosshairs does, then it willgo trough the dot

In first person perspective, sure. But my suggestion gets the object under the dot regardless of camera setup.

The dot is everytime in the middle, regardless of the perspective, because it would be weird, but if you show me a game, where my technique wouldn’t work, then you are right

Skyrim 3rd person. The blue guides are the exact middle. Also the 3rd person game I’m working on the crosshair is not quite in the center.