0
\$\begingroup\$
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    void Start()
    {

    }

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000))
            if (hit.transform.tag == "Interactable")
            {
                print("I'm looking at " + hit.transform.name);
            }
            else
                print("I'm looking at nothing!");
    }
}

This is working fine but this send raycast hit from the camera. I want to send the raycast from the mouse cursor so if the mouse cursor is moving over object it will detect it. Just instead the camera the mouse cursor.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You could use Camera.ScreenToViewportPoint https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
   void Update() {
       transform.position = Camera.main.ScreenToViewportPoint(Input.mousePosition);
   }
}

I could change your code as this.

void Update()
{
    Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
    RaycastHit hit;
    ...
}
\$\endgroup\$
2
  • \$\begingroup\$ This is seems to be working. But i have a problem if i'm standing too far from a door even if the door is big the raycasting hit on very narrow specific area on the door and detect the door. Only if i'm getting closer and closer to the door the area of detecting the object is getting bigger. How can i change the hitting area of the raycast ? \$\endgroup\$
    – Daniel Lip
    Commented Nov 9, 2017 at 7:04
  • 1
    \$\begingroup\$ If you want to change size of hitting area, you could use Physics.CapsuleCast. That api makes you can find objects in more larger area. \$\endgroup\$
    – whoo24
    Commented Nov 9, 2017 at 7:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .