Instantiate facing away from GameObject face

Hi,

I have the below script that passes the ray cast hit information to a GlobalVar.js

function Update () {
// Only continue if main camera
	if(Camera.main){
		var ray : Ray = Camera.main.ViewportPointToRay (Vector3(0.5,0.5,0));

		if (Physics.Raycast (ray, hit, 1000, myLayerMask)){
			globalVarsNetworkScript.rayCastHitTag = hit.collider.gameObject.tag;
			globalVarsNetworkScript.rayCastHitName = hit.collider.gameObject.name;
			globalVarsNetworkScript.rayCastTransform = hit.transform;
			globalVarsNetworkScript.rayCastHitPoint = hit.point;
			globalVarsNetworkScript.rayCastHitDistance = hit.distance;

		}
	}
}

Then in another script I’m trying to instantiate a prefab facing away from the GameObjects face where the ray cast hit, like a decal of a bullet hole, I thought this would do it but it does not work.

Instantiate(sparksPrefab, globalVarsNetworkScript.rayCastHitPoint, Quaternion.Euler(globalVarsNetworkScript.rayCastHitPoint.forward));

How would I do this please, Thanks.

Have you tried hit.normal, like globalVarsNetworkScript.rayCastHitNormal= hit.normal; Then use it in instantiation like Instantiate(sparksPrefab, globalVarsNetworkScript.rayCastHitPoint, Quaternion.Euler(globalVarsNetworkScript.rayCastHitNormal));

Get the same result .. [19072-screen+shot+2013-12-08+at+16.52.44.png|19072]

Create your bullet hole object using decal shader

1 Answer

1

You are going to need to pass the ‘normal’ from the ‘hit’ to this routine. Given the way you have thing structured, you will need to add a raycasthitNormal to the GlobalVar script and then add

 globalVarsNetworkScript.rayCastHitNormal = hit.normal;

Then the above code would use this for the rotation in the Instantiate:

Quaternion.LookRotation(globalVarsNetworkScript.rayCastHitNormal);

I get the error 'normal' is not a member of 'UnityEngine.Vector3'

Thanks to all who replied, robertbu will you convert your comment to an answer please as it worked and I'd like to accept it as the correct answer, thank you.

I moved the correct comment to the original answer.