0

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.

1 Answers1

0

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.

Nikaas
  • 564
  • 4
  • 8
  • "would like to know if there is a way to spawn it on the collisions instead of the origin of the object". The `hit.point` is actually the point of the collision. Check the [documentation](https://docs.unity3d.com/ScriptReference/RaycastHit-point.html) – rustyBucketBay May 09 '21 at 12:36
  • 1
    @rustyBucketBay He probably means collision/origin form the POW of the spawned object. – Nikaas May 09 '21 at 13:45
  • So, the collision "box" of the spawned object. Right now, I have the sphere, which is my spawned object. Whenever I try to spawn it, it clips through the floor and bounces out. I want to spawn it as if I were just placing the sphere on the ground, just to clarify. – Zany_Zachary1 May 10 '21 at 12:29
  • Neither of these worked. The same result is still there. – Zany_Zachary1 May 10 '21 at 16:54
  • I have tested it and the balls spawn on the surface. Here is the exact code I used: https://pastebin.com/6aM6qibs – Nikaas May 11 '21 at 11:04