- Home /
Create Bullethole with onCollisionEnter
Hey guys! I am scripting a shotgun and it have a prefab with multiple shots and that gun should have multiple bulletholes. That's what I made :
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "Bullet1")
{
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, 100f))
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}
}
But I don't know why that doesn't work.The bullet prefab also have Rigidbody and sphere collider.
Where is this script attached to? Is the collider a trigger?
But like that
if(col.gameObject.name == "Bullet1")
you test if the hitted collider is a bullet1. How about asking if it hits a wall?
It is your collider thing.
you need to make your bullet cast the ray in the update or fixedupdate and test if it hits a collider.
void Update ()
{
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, out hit, 100f))
{
if(hit.collider.tag == "walls")
{
Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
}
}
}
Test this out.
You're welcome. I just could write this as an answer, but i don't think it useful.
Answer by Hellium · Jun 19, 2015 at 07:34 PM
Why do you use a raycast ? Since the OnCollisionEnter has been called, you know that you have collided with something.
After testing the tag / layer of the collided object, If your bullet has hit the wall, you just have to instantiate the bullethole prefab at the following point Collision.contacts[0].point
and you also have the normal to the surface with Collision.contacts[0].normal
http://docs.unity3d.com/ScriptReference/Collision-contacts.html
By the way, "It doesn't work" doesn't help at all to understand what's the problem.
Answer by Maskeowl · Jan 31 at 09:06 PM
i want to use raycast but i cant i want to see bullet going idk how to do that with raycast
Your answer
Follow this Question
Related Questions
Destroy bullet on random collision 2 Answers
Need advice on non-realistic bullets collision vs distance 1 Answer
Optimization of bullet hit calculation per frame 1 Answer
How to detect correct collision from multiple game objects? Separate collisions 0 Answers
Have bullets be destroyed when they collide with ANY collider 0 Answers