I have a plane that is instantiated at the location of a RaycastHit. I have tried to make the plane align to the surface normal of the hit wall, but without success. Does anyone have a script that would do this simply?
Hallo, if you’re using a standard Unity Quad (due to the orientation of the pivot point, where the z-axis is pointing towards the surface), then this line of code should work:
Instantiate(quad, hit.point, Quaternion.FromToRotation(Vector3.back, hit.normal));
However, if you are using a standard Unity Plane with the pivot pointing the y-axis in the opposite direction of the surface, you must use Vector3.up
instead of Vector3.back
If Z-Fighting should cause problems, you can move the quad a little further forward:
Instantiate(quad, hit.point + hit.normal * 0.1f, Quaternion.FromTo bla bla...
To be on the safe side, here is a fully working code snippet, in which I used a Unity Quad:
public GameObject quad;
public float offset = 0.1f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
RaycastHit hit;
// shoots a raycast in the direction of the z-axis
Physics.Raycast(transform.position, transform.forward, out hit);
// only if we hit something
if (hit.collider)
{
Vector3 spawnPosition = hit.point + hit.normal * offset;
Quaternion spawnRotation = Quaternion.FromToRotation(Vector3.back, hit.normal);
Instantiate(quad, spawnPosition, spawnRotation);
}
}
}