Monday, 8 December 2014

Applying force in opposite direction of collision:

After banging my head to each and every script available and possible resource. I came up with the following code  It might help other people with the problem like kicking a football or 8-ball game or etc. The code is for 2D games in Unity, So here it is


public float explosionStrength = 10.0f;
void OnCollisionEnter2D(Collision2D collision) {
Collider2D collider = collision.collider;
 //Debug.Log("Collision with ball "+collider.name);
 if(collider.name == "FootBall")
 { GameObject target_=GameObject.Find("FootBall");
    Debug.Log("Velocity is "+target_.rigidbody2D.velocity.normalized );
    Vector2 forceVec = -target_.rigidbody2D.velocity.normalized * explosionStrength;                  target_.rigidbody2D.AddForce (forceVec, ForceMode2D.Impulse);
    Debug.Log("Collision with ball");
 }

 }

No comments:

Post a Comment