Home > database >  push object with add force in Unity3D
push object with add force in Unity3D

Time:05-26

I made top down shooter game where enemies are following the player. If they touch you, they push you with AddForce. I've managed to do that but only on specific direction. Problem is that if enemy is coming from player's right, they still gonna push you to the right and not to the opposite direction where they're coming from. I tried to detect enemy's rotation to add force to where they are looking. Here's the original script that works but it pushes only to the right:

public Rigidbody2d playerrb;
public GameObject enemy;
float force = 2f;

void OnCollisionEnter2D(Collision2D collision){
    playerrb.AddForce(transform.right * force, ForceMode2D.Impulse);
}

And here's what I've tried:

public Rigidbody2d playerrb;
public GameObject enemy;
float force = 2f;

void OnCollisionEnter2D(Collision2D collision){
    playerrb.AddForce(enemy.transform.rotation * force, ForceMode2D.Impulse);
}

CodePudding user response:

I would use the difference vector between player and enemy

public Rigidbody2d playerrb;
public GameObject enemy;
float force = 2f;

void OnCollisionEnter2D(Collision2D collision){
    var direction = (playerrb.position - enemy.transform.position).normalized;
    playerrb.AddForce(direction * force, ForceMode2D.Impulse);
}
  • Related