Raycasthit explanation wanted.
I'm trying to make a simple script that creates a cube on the place I click on a Plane. I figured I had to do that with RaycastHit, but there are no proper examples of what I want to achieve. Can someone please properly explain raycasthits and the likes, and also on which object I have to put the script on, eg: does the raycasthit only detects hits on the object the script is attached to?
Thanks in advance.
Huh, what? Offcourse not, I was trying to make a basic RTS test, but I had to know how raycasts worked, so I figured the easiest way to do so is to make a box spawn on the location of where I click on a plane. Nothing $$anonymous$$ecrafty about that.
Answer by Spk · Jul 14, 2011 at 02:27 PM
A raycast hit is not associated with any particular object. Essentially, you provide a starting position, direction and optionally a hitmask (to filter out what you want/not want to hit), and you eventually get back a RaycastHit record containing the various information you might need, including which GameObject has been hit, along with the intersection point and normal.
In your case, you just need to create a new script, called whatever, where you will put your input & raycast logic.
In Update() you will monitor the click event from the user. When this happens, you should call a function with the following pseudo/sample code:
// create a ray going into the scene from the screen location the user clicked at
Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
// the raycast hit info will be filled by the Physics.Raycast() call further
RaycastHit hit;
// perform a raycast using our new ray.
// If the ray collides with something solid in the scene, the "hit" structure will
// be filled with collision information
if( Physics.Raycast( ray, out hit ) )
{
// a collision occured. Check if it's our plane object and create our cube at the
// collision point, facing toward the collision normal
if( hit.collider == yourPlaneCollider )
Instantiate( yourCubePrefab, hit.point, Quaternion.LookRotation( hit.normal ) );
}
Hope this helps.
That's really helpful! For clarification, could you please explain the syntax out hit
? Does this somehow initialize hit
, allowing Physics.Raycast
to deter$$anonymous$$e where the collisions are along the ray? Also, what if there are multiple collisions along the ray?
Answer by Skjalg · Jul 14, 2011 at 02:09 PM
Isn't your question answered here ? http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html?from=RaycastHit
hitInfo will contain more information about where the collider was hit (See Also: RaycastHit).
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
Debug.DrawLine (ray.origin, hit.point);
}casting a ray.