How to apply knockback on collision (2D)

Here is the code for my player movement:

function Update () {

		animator.SetInteger("Direction", 4);

	if (Input.GetKey(moveUp) && isGrounded == 0)
	{
		rigidbody2D.velocity.y = jumpheight;
		isGrounded = 1;
		animator.SetInteger("Direction", 2);
	}
	
	
	else if (Input.GetKey(moveLeft))
	{
		transform.position += Vector3.left * speed * Time.deltaTime;
		animator.SetInteger("Direction", 3);
	}
	else if (Input.GetKey(moveRight))
	{
		transform.position += Vector3.right * speed * Time.deltaTime;
		animator.SetInteger("Direction", 1);
	}
	
}

And here is the code for the collision:

var PlayerHealth = 100.0;
function Start () {

}

function Update () {

}

function OnCollisionEnter2D(coll: Collision2D) {
 		
		if (coll.gameObject.tag == "Ghost"){
		PlayerHealth = PlayerHealth - 5.00;
		rigidbody.AddForce (Vector3.left * 10);
		}
		

}

The add force has no effect on my character. The collision works though, as the players health goes down. I’m pretty certain it has to do with the transform position in my movement, but I’m not sure how to fix it. Any help?

As Pyrian said, you cannot combine the physics engine whilst hard-setting the position. However, you can turn the physics engine on and off by setting the RigidBody.isKinematic variable.

Whilst this is on, you can set your position manually as before, and when you want the physics to take over (such as when a collision happens), you turn it off and make sure that you do not make any more position updates until it’s back on again. The physics engine should take care of the rest.

Looking at your code, perhaps you could wrap that in an if statement that checks whether or not it is currently kinematic - if it is, do standard control stuff. If it’s off, you’ll need to wait until your collision is ‘finished’ before it turns back on.

Maybe something like:

function Update() {
  if (rigidbody2D.isKinematic) {
    // Do Input key positional stuff
  } else {
    // Wait for collision to finish
    if (collisionIsFinished()) {
      rigidbody2D.isKinematic = true;
    }
  }
  
  // other things
}

bool collisionIsFinished() {
  // code that checks when your collision is done or whatever
}

and then in the player code, add one simple change:

function OnCollisionEnter2D(coll: Collision2D) {

  if (coll.gameObject.tag == "Ghost"){
    PlayerHealth = PlayerHealth - 5.00;
    rigidbody.AddForce (Vector3.left * 10);
    rigidbody2D.isKinematic = false;
  }