unity add force away from object code example
Example 1: unity push in opposite direction of collision
void OnCollisionEnter(Collision c)
{
float force = 3;
if (c.gameObject.tag == "enemy")
{
Vector3 dir = c.contacts[0].point - transform.position;
dir = -dir.normalized;
GetComponent<Rigidbody>().AddForce(dir*force);
}
}
Example 2: how to add a force to an object unity
private Rigidbody2D rb;
public Vector2 direction;
public float force;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.AddForce(direction * force, ForceMode2D.Impulse);
}