Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

push object with add force in Unity3D

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading