Search Unity

Clash of Sword RigidBody2D

Discussion in '2D' started by oscarjcs, Sep 23, 2018.

  1. oscarjcs

    oscarjcs

    Joined:
    Jun 8, 2018
    Posts:
    9
    Hello Everyone!
    I want to make two "sword" hit each other and the players step back or just repel each other. I couldn't find any solution, except pointeffector2d. But, this effect is not what I want.
    I have a boxcollider2d as a trigger, circlecollider2d also as a trigger (both in front of my character) and a rigidbody2d. The parent (is the character) also have a RigidiBody2D and other colliders and gravity of 5.
    When I hit X button, start the animation and the boxcollider2d and the circlecollider2d are enable until the end of the animation.
    The reason I use a trigger is because the player could be closer to the enemy, and the sword can hit the enemy and not just "air" or empty space. Also, if is not a trigger, when the colliders are enable and hit the enemy rigidbody2d, have a random behavior.
    I find a similar code and I thought could be useful, but didn't work
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class colliderAttack : MonoBehaviour
    6.  
    7. public float force = 300f;
    8. public bool hasHit = false;
    9.  
    10. void OnTriggerEnter2D (Collider2D swordAttack)
    11. {
    12. if (swordAttack.gameObject.tag == "Sword" && !hasHit)
    13. {
    14. hasHit = true;
    15. StepBack();
    16. }
    17. }
    18.  
    19. void StepBack()
    20.     {
    21.         CircleCollider2D collision = gameObject.GetComponent<CircleCollider2D>();
    22.         if (collision.gameObject.tag == "Sword")
    23.         {
    24.             Vector2 dir = GetComponentInParent<Rigidbody2D>().transform.position - collision.transform.position;
    25.             dir = -dir.normalized;
    26.             GetComponentInParent<Rigidbody2D>().AddForce(dir * force, ForceMode2D.Impulse);
    27.             Debug.Log(dir);
    28.         }
    29.     }
    30.  
    If someone could help me to find a solution or give me a better way to do the clash of sword I will be grateful...
    Thanks!!!