Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

AddForce isn't working in unity 2D.

Discussion in '2D' started by NotTimTam, Mar 22, 2019.

  1. NotTimTam

    NotTimTam

    Joined:
    Sep 24, 2015
    Posts:
    20
    So, here's the deal. I want to have a dash attack in my game, where the player is launched forward when they hit the attack button. This will be a quick burst, not an endless one. Sort of like you see here:

    Basically, to program this, I want it to thrust the player in the direction they are going for a short amount of time. I got an addforce component working. The only problem is that it will thrust the player the AttackForce amount on the x and y planes, instead of in the current direction. Here is that:
    Code (CSharp):
    1. this.GetComponent<Rigidbody2D>().AddForce(new Vector3(AttackForce, AttackForce), ForceMode2D.Impulse);
    That is rubbish and doesn't suit my needs. But, when I try to do it in the ways I have seen other people say, nothing happens...
    Here is that:
    Code (CSharp):
    1. this.GetComponent<Rigidbody2D>().AddForce(currentvector2position * AttackForce, ForceMode2D.Impulse);
    It does nothing. :(
    Here is the rest of the code if you need it:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public PlatformerCharacter2D pc2d;
    8.     private bool has_attacked = false;
    9.     private float cooldown = 1.0f;
    10.     public float AttackForce = 3.0f;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         has_attacked = false;
    16.     }
    17.  
    18.     IEnumerator Countdown()
    19.     {
    20.         yield return new WaitForSeconds(cooldown);
    21.     }
    22.  
    23.     // Update is called once per frame
    24.     void Update()
    25.     {
    26.         if (pc2d.m_Grounded)
    27.         {
    28.             has_attacked = false;
    29.         }
    30.         if (Input.GetButton("Fire1") & !has_attacked)
    31.         {
    32.             Debug.Log("Player 1 Attacked!");
    33.             this.GetComponent<Rigidbody2D>().AddForce(ForceMode, ForceMode2D.Impulse);
    34.             has_attacked = true;
    35.             StartCoroutine(Countdown());
    36.         }
    37.     }
    38. }
    39.  
     
  2. NotTimTam

    NotTimTam

    Joined:
    Sep 24, 2015
    Posts:
    20
    Actually, they both do the same thing. The second one also launches the player up and forward instead of in the current direction.

    And in the full script on line 21 where it says forcemode the first time, it is supposed to say:
    Code (CSharp):
    1. this.transform.position * AttackForce