I have a obstacle.When the player hits the object, it will be push back.I want to determine the direction of the object being pushed based on where it hits.
Are you saying you want to add a force to push the player away when it hits something? The easiest way would be to give the object they are colliding with a PhysicMaterial with a very high bounciness value (probably also set the bounce combine to Maximum). Then the physics engine will bounce it away for you and you wont have to add any forces yourself.
If you do want to do this with AddForce, you can get the direction in a few ways. The easiest would be to just calculate the difference between the two objects in OnCollision:
public Rigidbody rigidbody;
public float pushBackForce;
private void OnCollisionEnter(Collision collision) {
Vector3 fromHitToPlayer = transform.position - collision.transform.position;
rigidbody.AddForce(fromHitToPlayer.normalized * pushBackForce);
}
the vector is normalized to make sure you dont add a bigger force the further away the objects are. Depending on how precise you need to be, and what works better for your set up, you can replace “collision.transform.position”, with a few different things, such as the actual hit point or the position of the collider the player hit, both of which can be got from the collision object.