- Home /
How to get mouse cursor position on plane and set an object's position at this point?
I have a simple code where i have vert/horiz rotation enebled cannon controled using arrows, and what i want to do now is to take control over this cannon with mouse. What i need is to get mouse position on invisible plane and move my 3D cursor to place where mouse cursor collides with plane using raycast... and here's my problem: How do i get this position and use it later on?
Have a Vector3 member variable on your script, which you can call on later.
Answer by aldonaletto · Oct 31, 2011 at 03:02 PM
You must choose a point and a normal vector to create the plane, use camera.ScreenPointToRay to create a ray from the mouse pointer, Plane.Raycast to find the distance from the ray start and Ray.GetPoint to finally find the 3D point. The script below creates a horizontal plane passing through the object to which the script is attached, create the ray, do the raycast etc.:
function Update(){ // this creates a horizontal plane passing through this object's center var plane = Plane(transform.position, Vector3.up); // create a ray from the mousePosition var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // plane.Raycast returns the distance from the ray start to the hit point var distance: float; if (plane.Raycast(ray, distance)){ // some point of the plane was hit - get its coordinates var hitPoint = ray.GetPoint(distance); // use the hitPoint to aim your cannon } }
Big Thanks aldonaletto! I can finally move on forward in this JavaScripted madness ^^/
Answer by The_Mean_Fiddler · May 24, 2015 at 02:38 PM
Thanks for this. It works great
You got a bit wrong though. it's var plane = Plane(Vector3.up, transform.position);
Your answer
![](https://koobas.hobune.stream/wayback/20220613025445im_/https://answers.unity.com/themes/thub/images/avi.jpg)