- Home /
Instantiating a prefab facing away from it's collision point?
I have seen this being done with Raycast in mind, but is it possible with OnCollisionEnter, ContactPoint?
Like if I have an asteroid crashing into a planet, it spawns a prefab with a mushroom cloud particle system that has to be facing away from the surface of the planet. How will I go about instantiating the prefab with it's Y-axis facing away from the surface it collided with?
This is the script that I have made for this purpose, but it doesn't have the facing-away business to it:
var explosion: GameObject;
function OnCollisionEnter(collision : Collision) {
for (var contact : ContactPoint in collision.contacts)
{
if(contact.otherCollider.gameObject.name.Contains("Rock")){
Instantiate(explosion, contact.point, Quaternion.identity);
Destroy(gameObject);
}
}
}
Answer by robertbu · Mar 17, 2014 at 04:21 AM
Assuming you build your model so that the part of the model you want to point away from the surface is the 'up' of that model, you can do this:
if(contact.otherCollider.gameObject.name.Contains("Rock")){
var q = Quaternion.FromToRotation(Vector3.up, contact.normal);
Instantiate(explosion, contact.point, q);
Destroy(gameObject);
}
Well, the planets that the asteroid crashes into are spherical and has sphere colliders. $$anonymous$$aking the prefab pointing away from the center is what I'm trying to achieve.
It is hard for me to give exact code with more context. Is this code on the planet? If so, you can get your normal vector like:
var normal = contact.point - transform.position;
Then the same code using this normal:
var q = Quaternion.FromToRotation(Vector3.up, normal);
Instantiate(explosion, contact.point, q);
Again this code is assu$$anonymous$$g that you've built your model that you instantiate so that the 'up' of the model wants to point along the normal.
The script that spawns the explosion prefab is on the asteroid which is going to hit the planet. And the explosion prefab will be instantiated pointing away from the planet. You could easily assume this because the script has "Destroy(gameObject)" in it, since it's not the planet that gets destroyed, what would the mushroom cloud be good for then?
@SYRSA - you are probably right. What lead me astray is that the name of the other object is 'Rock', which seemed like a name for the asteroid rather than the planet. So if what you say is true, then the normal could be calculated like:
var normal = contact.point - contact.otherCollider.transform.position;
Thanks, Rob. You sure are nice helping around. The script works beautifully now.