- Home /
how to cast a ray from an empty game object toward mouse position.
hey guys, i been searching for this matter an all i find is casting a ray from camera toward the mouse position.that's not what i want.i have empty game object which is my camera's parent and i want to cast a ray from that empty game object toward the mouse position.(i can't ray cast from my camera because its occupied with something else).is there any way to do that? here is the script i been working with but its not working as i needed it.
void Update()
{
Ray ray = new Ray(this.transform.position, Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, distance ,layers))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
objectToPlace.position = hit.point;
}
Answer by Hellium · Jun 12, 2019 at 05:22 PM
The Ray constructor takes an origin and a direction, but Input.mousePosition
is the position of the mouse in the screen space....
So you will need to find a way to get that direction from the mouse position. Since you haven't provided much details, it will be hard to give an adequate answer.
private Camera cam;
void Start()
{
cam = Camera.main;
}
void Update()
{
Vector3 screenPoint = Input.mousePosition ;
screenPoint.z = cam.farClipPlane; // Change according to your needs
Vector3 worldPoint = cam.ScreenToWorldPoint( screenPoint ) ;
Vector3 origin = transform.position;
Vector3 direction = (worldPoint - origin).normalized ;
Ray ray = new Ray( origin, direction );
// ...
}
assume my camera has a parent which is just an empty game object.how can i cast a ray from an empty game object toward mouse position without mentioning any camera in my script
You need a reference to a camera (the one rendering the output on the screen) in order to convert the mouse position from screen space to world space.