Swati Rawat
Swati Rawat

Reputation: 1729

OnCollisionEnter2D incorrect contact point? - Unity2D

I am trying to shoot a bullet (rigidbody2d, boxcollider2d) to another enemy object (rigidbody2d, kinematic, circlecollider2d). I want the collision point between these two. When they collide, i want a collision particle effect and from the contact point, i want to create 5 rock objects all moving in different directions. How should i achieve this? Problem is that, the contact point i get seems incorrect. Collision particle effect is created when collision happens but the rock objects are created in some other point close to the contact point but not the contact point. Also how to i move the rock objects in different directions after instantiating them?

my code:

void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Enemy")
{
    ContactPoint2D contact = coll.contacts[0];

    GameObject rock1 =  Instantiate (rock, contact.point, transform.rotation) as GameObject;
    rock1.rigidbody2D.velocity = transform.up * 20;
    GameObject rock2 =  Instantiate (rock, newPos, transform.rotation) as GameObject;
    rock2.rigidbody2D.velocity = transform.right * 20;
    Destroy(coll.gameObject);
    Destroy (gameObject);
    Instantiate (explosion, transform.position, Quaternion.identity);           

}

}

Upvotes: 0

Views: 974

Answers (1)

Anas iqbal
Anas iqbal

Reputation: 1044

For your first problem [Rocks spawning at another point other than contact point]

I recommend you to remove a box collider from your bullet as box collider has a flat surface and will generate multiple contact points on collision. Use Circle collider instead. (No limitations on the rock).

For your second problem [How to spawn and throw rocks in different direction]

The contact points you get from collision have a normal vector in them (contact.normal) which provide you the normal vector to the collision point.

Apply some random rotation on your rock and use this normal vector for the direction in which you want to move your rocks. Also Collision2D contains a relativeVelocity vector. You can also ADD this to your normal vector (It might give a little realistic physics effect :) ).

Also the rocks you instantiate should not have isKinematic set to true or AddForce and Velocity will have no effect on the rock.

Upvotes: 0

Related Questions