- Home /
 
How To: Spawn object on raycast collision.
I have created a plane in my scene that can be used to detect collision. I am trying to create a raycast on mouse click and detect if it's collided with that game object. Then instantiate another game object. I can't seem to figure out how to do this.
// Update is called once per frame void Update() { if(Input.GetButtonDown("Fire1")) { Ray ray = new Ray(Camera.main.transform.position, Vector3.Normalize(near)); Vector3 near = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0)); RaycastHit[] raycastHits = Physics.RaycastAll(ray);
 
                        if(raycastHits == GameObject.FindGameObjectWithTag("S_Plane"))
         {
         }
     }
 }
  
                
Answer by mattirwin · Feb 09, 2011 at 03:24 PM
Try something like this:
if(Input.GetButtonDown("Fire1"))
{
    Ray ray;
    RaycastHit hit;
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit, 100.0f))
    {
        if (hit.collider.name=="S_Plane") 
            Instantiate(myPrefab, hit.point, Quaternion.identity);
    }
}
 
                
                
               I believe you can also use collider.Raycast in a script on a given object to limit the raycast hit check to that object.
Answer by Tobs 1 · Feb 09, 2011 at 04:50 PM
var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; var layerMask = 1 << 8; var Dummy:GameObject;
  
               if (Input.GetButtonDown ("Fire1")) { if (Physics.Raycast (ray, hit, Mathf.Infinity, layerMask)){ placedObj = Instantiate(Dummy, Vector3(hit.point.x, hit.point.y, hit.point.z) , Quaternion.identity); } } 
Something like this :)
Your answer
 
             Follow this Question
Related Questions
problem with instatiated clone 2 Answers
help with scripting combo points 1 Answer
checking collision with polygon collider using ray cast and instantiating objects issue 1 Answer
Raycast bullet impact and instantiating particles 3 Answers
Attaching a joint on the instantiated object and connecting it with the collided object. 1 Answer