Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

RigidBody2D.addForce not working when called via UIButton

Discussion in 'Physics' started by jeremydulong, Jul 17, 2018.

  1. jeremydulong

    jeremydulong

    Joined:
    Nov 9, 2017
    Posts:
    11
    I am applying custom "gravity" to my ball object via a constant force using FixedUpdate because I don't want to use the typical downward pull, but I want to also add an impulse force (to make the ball jump) when the player taps a button. I thought the easiest way to do this would be to just make the button on click function call an opposite force as the custom gravity - in the code below I'm trying to use 3 for gravitationalPull and -5 for jumpForce - but nothing is happening when I press the button. The button does call the function, I added a log message to test this. And the console gives no errors.

    Code (CSharp):
    1. public class Gravity : MonoBehaviour {
    2.  
    3.     public GameObject ball;
    4.     public float gravitationalPull;
    5.     public float jumpForce;
    6.  
    7.     void FixedUpdate () {
    8.         ball.GetComponent<Rigidbody2D> ().AddForce ((this.transform.position - ball.transform.position).normalized * gravitationalPull);
    9.     }
    10.  
    11.     public void jump() {
    12.  
    13.         ball.GetComponent<Rigidbody2D> ().AddForce ((this.transform.position - ball.transform.position).normalized * jumpForce, ForceMode2D.Impulse);
    14.  
    15.     }
    16.  
    17. }
     
    Last edited: Jul 17, 2018
  2. jeremydulong

    jeremydulong

    Joined:
    Nov 9, 2017
    Posts:
    11
    Bad testing on my part. Due to forces also being applied via surface effectors I just needed to increase the force value... a lot. 800 works a lot better than 5.
     
unityunity