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?
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
}
}
Thanks for this. It works great
You got a bit wrong though.
it’s
var plane = Plane(Vector3.up, transform.position);