Search code examples
c#unity-game-engineinstantiation

Instantiate from raycast without intersect


So I want to know how to instantiate a GameObject without intersection in Unity3D. As of now, the sphere instantiates intersected with the object that I hit with the raycast. I am using the location of hit.point, but would like to know if there is a way to spawn it on the collisions instead of the origin of the object. Here is my code for reference:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BallSpawn : MonoBehaviour
{
    public int castLength = 100;
    public GameObject spawnObject;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //Input.GetMouseButton for infinite
        if (Input.GetMouseButton(0))
        {
            SpawnBall();
        }
            

    }

    public void SpawnBall()
    {
        RaycastHit hit;
        
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * castLength, Color.green, Mathf.Infinity);
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, castLength))
        {
            Instantiate(spawnObject, hit.point, hit.transform.rotation);
        }
    }
}

As of now, the spheres clip into the ground and bounce out when they are spawned. I would like it for the spheres to be "placed" so to speak, so that they spawn without clipping.


Solution

  • You can try to replace hit.point with hit.point + hit.normal * ballRadius (of course you must know or be able to get what the ball radius is). But this will result with some spawn positions being off, especially if you hit a surface under small angle.

    Better alternative is to replace ray cast with Physics.SphereCast (transform.position, sphereRadius, transform.forward, out hit, castDistance). This should give you good results but again you will still have to add the ball radius along the hit normal just like the raycast.