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

ForceMode.Impulse object movement stops when key is released

Discussion in 'Physics' started by josealfu, Aug 27, 2022.

  1. josealfu

    josealfu

    Joined:
    Jan 16, 2022
    Posts:
    4
    Hello, I just made this simple script which makes my gameObject moves in diagonal directions. D key for right/up movement and A key for left/up movement. I want the movement to continues until gravity stops it and gameObject starts to falling to the ground. This happens just fine with Y force, the gameObject keep ascending til gravity makes its job but for unknow reason X force just instant stops once key is released.

    Code (CSharp):
    1.  
    2.     private float _forceX = 10f;
    3.     private float _forceY = 5f;
    4.  
    5.     void FixedUpdate()
    6.     {
    7.         KeyboardController();
    8.     }
    9.  
    10.     void KeyboardController()
    11.     {
    12.         var _rb = GetComponent<Rigidbody>();
    13.  
    14.         if (Input.GetKey(KeyCode.D))
    15.         {
    16.             _jetpackParticle.Play(); // Parcticle system
    17.             _rb.AddForce(new Vector3(_forceX, _forceY, 0), ForceMode.Impulse);
    18.             _anim.SetBool("isMirrorFlying", false); // Animator
    19.  
    20.         }
    21.         else if (Input.GetKey(KeyCode.A))
    22.         {
    23.             _jetpackParticle.Play(); // Parcticle system
    24.             _rb.AddForce(new Vector3(_forceX * -1, _forceY, 0), ForceMode.Impulse);
    25.             _anim.SetBool("isMirrorFlying", true); // Animator
    26.         }
    27.         else
    28.         {
    29.             _jetpackParticle.Stop(); // Parcticle system
    30.         }
    31.     }
    Also, when checking the info section on the rigidbody component I can see how speed on Y is increased while speed on X keeps at zero even when the gameObject is moving on X axis on the playmode screen.


    Thanks!
     
    Last edited: Aug 27, 2022
  2. josealfu

    josealfu

    Joined:
    Jan 16, 2022
    Posts:
    4
    Ok, the problem always was the animator in my object. It seems animations touch rigidbody somehow.

    What I did is put my original object inside a new empty object then delete the rigidbody component from my original object and create a new one in the parent object.