Search Unity

Addforce only works when pressing button

Discussion in 'Scripting' started by mrtlns, Aug 29, 2019.

  1. mrtlns

    mrtlns

    Joined:
    Aug 8, 2018
    Posts:
    3
    Hello everyone,
    first of all english is not my native language so i hope i make myself understand. Also it's my first time here!

    I'm making a 2d game for android. I created buttons to move a ball left (buttonLeft) and right, added an event trigger in each of them,(Pointer Down and Pointer Up) dragged the character controller in it and then selected the function for each button.
    In the script I created three public voids. Leftmove() and Rightmove() for PointerDown event trigger.
    Code (CSharp):
    1. public void Leftmove()
    2.     {
    3.         gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(-1000f * Time.deltaTime, 0));
    4.                Debug.Log("Leftmove");
    5.     }
    The third void is MoveStop() as a function for the Pointer Up event trigger.
    Code (CSharp):
    1. public void MoveStop()
    2.     {
    3.         gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0 * Time.deltaTime, 0));
    4.                Debug.Log("Stopmove");
    5.     }
    The problem is that the ball only moves one time when pressed and not continuously adding force. I want it to keep moving left as long as I keep pressing the button, and stop when It's released.
    Thank you for your help in advance.
     

    Attached Files:

  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Do something like:
    Code (csharp):
    1.  
    2. bool moving = false;
    3. public void StartMove() {
    4. moving = true;
    5. }
    6. public void EndMove() {
    7. moving = false;
    8. }
    9. void FixedUpdate() {
    10. if (moving)
    11.         gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0 * Time.deltaTime, 0));
    12. }
     
    mrtlns likes this.
  3. mrtlns

    mrtlns

    Joined:
    Aug 8, 2018
    Posts:
    3
    Wow, that solved the problem! Thanks a lot StarManta. :D