Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[2D] Object Knockback [RPG]

Discussion in 'Scripting' started by Ericks89, Sep 19, 2017.

  1. Ericks89

    Ericks89

    Joined:
    Nov 3, 2012
    Posts:
    39
    How would I go about creating a knock back for an object based on direction of where the player or enemy attacks?

    I believe this would go in something like void onCollisionEnter2D(Collision2D col)

    Code (csharp):
    1.  
    2.     // vec1 is the player and vec2 is the enemy
    3.     movdir = Mathf.Rad2Deg(Mathf.Atan2(vec1.transform.position.y - vec2.transform.position.y, vec2.transform.position.x - vec1.transform.position.x));
    4.     if (col.gameObject.tag == "Enemy") {
    5.         rb.AddForce(movedir * thrust);  
    6.     }
    7.  
    I believe I got most of it right, but looking for clarification.
     
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    You dont need to use circle math just do:

    Code (CSharp):
    1. Vector3 moveDir = vec1.transform.position - vec2.transform.position;
    2. moveDir.z =0.0f;
    3. moveDir.normalise();
    4.  
     
  3. Ericks89

    Ericks89

    Joined:
    Nov 3, 2012
    Posts:
    39
    Wouldn't you want Vector2 over Vector 3 unless I'm missing something?
     
  4. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    The z axis is used for depth on 2d, so you can control sorting order.
     
    Ericks89 likes this.