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.