Search Unity

Resolved A different force each time

Discussion in 'Physics' started by arencg, May 24, 2023.

  1. arencg

    arencg

    Joined:
    Mar 18, 2022
    Posts:
    21
    I defined that if the player enters an area that I specified, a force will be added to him to jump, but I don't know why a different amount of force enters the player every time.


    Code (CSharp):
    1.  private void jump()
    2.         {
    3.             JumpZero();
    4.             if ( _grounded)
    5.             {
    6.                 if (jumpTrue )
    7.                 {
    8.                     //Local Direction to World direction!
    9.                     var worldForceDirection = localToWorldMatrix.MultiplyVector(localForceDirection);
    10.                
    11.                     //Add force to local Y axle
    12.                     playerRig.AddForce(transform.up * forceJump,ForceMode.Impulse);
    13.                 }
    14.             }
    15.         }
    16.  
    17.         void JumpZero()
    18.         {
    19.             jumpTrue = Physics.CheckSphere(dPoint1.position, dPontRadius, jumpZone) || Physics.CheckSphere(dPoint2.position, dPontRadius, jumpZone);
    20.             playerAnim.SetBool("Jump",jumpTrue);
    21.             StartCoroutine(SetJumpToFalse(0.5f));
    22.         }
    23.         IEnumerator SetJumpToFalse(float delay)
    24.         {
    25.             yield return new WaitForSeconds(delay);
    26.             jumpTrue = false;
    27.         }
     
  2. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,929
    How's "_grounded" determined?

    Your code might apply a force for more than one frame while the character is inside the jumpZone, since jumpTrue is set to false after 0.5 seconds once he first enters it. Many frames can be rendered in 0.5 seconds.

    Only "_grounded" and "jumpTrue" can keep the force from being added, so unless _grounded is only true for a single frame, you might be adding a force for a variable (essentially random) amount of frames.
     
    arencg likes this.
  3. arencg

    arencg

    Joined:
    Mar 18, 2022
    Posts:
    21
    _grounded controlled by:
    Code (CSharp):
    1.  
    2. public void Grounded()
    3. {
    4.     _grounded = Physics.CheckSphere(dPoint1.position, dPontRadius, groundLayer) || Physics.CheckSphere(dPoint2.position, dPontRadius, groundLayer);
    5. }
    6.  
    how can i control
     
    Last edited: May 24, 2023
  4. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,929
    Given your code, I see no reason to not set jumpTrue to false right after the character jumps, instead of waiting for half a second.

    However, I’d suggest you to use triggers and OnTriggerEnter to make the character jump when entering the jump zones. That’s a lot simpler and more reliable than using physics queries -such as CheckSphere- and coroutines.
     
    arencg likes this.