Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Bouncing ball

Discussion in 'Physics' started by Andrew203, Dec 7, 2018.

  1. Andrew203

    Andrew203

    Joined:
    Apr 23, 2018
    Posts:
    35
    Hi, Im trying to make a game similar to helix jump, but have a small problem with a bouncing ball. Currently im trying to use Raycasting to check if ball is close to ground and then use rigidbody.addforce with Forcemode set to impulse. It looks pretty nice but the problem is that I have bounce animations where ball gets flat for a second. I dont know why but the whole function gets triggered twice, i've tried adding timers and booleans but it doesnt change anything. Here's code
    Code (CSharp):
    1. public class BallPhysics : MonoBehaviour {
    2.  
    3.     Rigidbody rb;
    4.     Animator anim;
    5.     float Gravity = -9.8f;
    6.     float JumpForce = 35f;
    7.  
    8.     void Start ()
    9.     {
    10.         rb = GetComponent<Rigidbody>();
    11.         anim = GetComponent<Animator>();
    12.     }
    13.  
    14.  
    15.     void FixedUpdate ()
    16.     {
    17.      
    18.  
    19.         rb.AddForce(Gravity*Vector3.up);
    20.         Jump();
    21.     }
    22.  
    23.     void Jump()
    24.     {
    25.         if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), 0.55f))
    26.         {
    27.             rb.AddForce(JumpForce * Vector3.up, ForceMode.Impulse);
    28.             anim.SetTrigger("Bounce");
    29.         }
    30.     }
    31.  
    32. }
     
  2. N_Murray

    N_Murray

    Joined:
    Apr 1, 2015
    Posts:
    85
    Hi, Fixed Update can get called more than once per frame so it is calling your function more than once. Try creating a boolean which get set to false in your jump function then set to true again in LateUpdate. Hope that helps