- Home /
How can i use raycast hit to detect object by the object tag name ?
This is working since i want the raycast send the hit from the mouse cursor position. The problem is if i have a big door for example and i'm standing a bit far from the door it will detect the door only on specific area on the door. But if i'm getting closer and closer to the door the hitting area is getting bigger.
So it's logic that if the door is big enough that it will detect the door even from a bigger distance i mean on every place/area that is the door. If the object that have the tag "Interactable" is smaller then the hitting area should be smaller.
In other words i need somehow to find the object area and then to make that it will detect it when it hit on every place of the object.
Maybe i should add every object with tag "Interactable" some collider ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRaycast : MonoBehaviour
{
public Camera cam;
void Update()
{
Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
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!");
}
}
Answer by Daemonhahn · Nov 09, 2017 at 11:09 AM
That looks fine, you probably need to add a collider to each object, and make sure they have the Interactable tag.
EDIT: you are likely not using the correct transformation space
try looking at:
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
https://docs.unity3d.com/ScriptReference/Camera.ScreenToViewportPoint.html
https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
etc, try them all until you find the correct space you need. It is likely you have used the incorrect method.
I would try screen point to ray, or even screen to world point and then a ray cast there.
Your answer
Follow this Question
Related Questions
How can I make that the interactable raycast shoot will not pass through some objects like doors ? 1 Answer
Why the player is keep moving sometimes out of the grid area ? 0 Answers
Script for a hue rainbow scroll on the material 1 Answer
How can i make the camera to lookat the next target and then rotate and move to the next target ? 0 Answers
Another Raycast Issue. 0 Answers