- Home /
Issues with instantiated prefabs transform using hit.point?
Hello,
I am running a simple test scene trying to instantiate a prefab composed of a large number of small cubes at the hit point of a raycast. The scene is composed of a simple cube falling towards a plane. As the cube falls a raycast is used to check the tag of the plane below. Based on this tag the physic material of the cube is changed. In this case if the tag is set to 0, a prefab composed of 2000+ cubes is created at the hit.point of the raycast. Currently the raycast works and the cubes are created but I can't seem to get the position and rotation of the cubes correct. The script I am using and some pictures of the issues can be seen attached. The script is just attached to the falling cube object. I have tried a couple different position and quaternion inputs but all result in the cubes instantiating well above or below the plan, or with a wonky rotation. I am looking for the cubes to be just above and parallel to the plane. Any help with this problem would be greatly appreciated!
public class RestitutionCheck : MonoBehaviour {
public PhysicMaterial[] slopeMaterials;
public GameObject talusRocks;
private Rigidbody thisRock;
private Vector3 thisRockPosition;
private Collider slopeObject;
private Collider rockCollider;
private bool talusOff;
// Use this for initialization
void Start () {
thisRock = this.GetComponent<Rigidbody>();
rockCollider = thisRock.GetComponent<Collider>();
thisRockPosition = rockCollider.transform.position;
talusOff = false;
}
// Update is called once per frame
void Update () {
Ray ray = new Ray(thisRock.transform.position, Vector3.down);
Debug.DrawRay(thisRock.transform.position, Vector3.down, Color.green);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1.5f, 1<<10))
{
string slopeTag = hit.collider.tag;
slopeObject = hit.collider;
int slopeInt;
if (!int.TryParse(slopeTag, out slopeInt))
{
Debug.LogError("Slope tag parse failed");
}
switch (slopeInt)
{
case 0:
Console.WriteLine("slopeTag =" + slopeInt);
rockCollider.material = slopeMaterials[0];
if (!talusOff)
{
Instantiate(talusRocks, hit.point + (hit.normal * 0.4f), Quaternion.LookRotation(hit.normal));
talusOff = true;
}
break;
case 1:
Debug.Log("slopeTag =" + slopeInt);
rockCollider.material = slopeMaterials[1];
break;
}
}
Debug.Log("no hit detected.... no change to slope material");
}
}
Your answer

Follow this Question
Related Questions
Raycast not finding collider when instantiated from code 1 Answer
My Raycast on awake fires and will not change Help! 0 Answers
Instantiate, null reference and Raycasting problem. 2D 1 Answer
In terms of performance, which one is faster, 2D raycast, collission or distance sorting? 0 Answers
Getting raycast to fire at touch position but only when second finger is on screen 0 Answers