- Home /
Get Vector3 of Position Clicked on Plane
I want to click on a 3D plane with my mouse. When I do this, I want it to return a Vector3
of where I clicked. When I use:
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
then, it gives me the Vector3 of the center of the plane. Not what I want. I want it to be at the position I click.
I am trying to create a Ray
(`Camera.ScreenPointToRay`) and work with Physics.Raycast
, but that just returns a bool
, and not where it actually hits.
I have spent the last 3 hours reading everyone else's questions...what am I missing here?
Answer by robertbu · May 16, 2014 at 05:02 AM
If you look at the reference page for Physics.Raycast(), you will see there are many forms of this function...ones that have different signatures (i.e. different parameters). You need one that take a RaycastHit as a parameter. Here is an example of a raycast from the mouse that reports the position of the hit:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
void Update() {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
Debug.Log("The ray hit at: "+hit.point);
}
}
}
Thank you so much!! I have that exact code but without the keyword out!! (I am still fairly new to C#). I would upvote if I was allowed, but 15 rep $$anonymous$$imum. They don't make it easy to be a new member here...
Note in most reference pages, you can select the language to get code samples in a specific language. Javascript does not need the 'out' keyword, but C# does.