Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Bugging when I try to Walk and Jump at the Same Time

Discussion in 'Physics' started by FGPArthurVII, Jul 15, 2016.

  1. FGPArthurVII

    FGPArthurVII

    Joined:
    Jan 5, 2015
    Posts:
    106
    Hi, I am trying to make my character jump, but when I am walking and try to jump it fells like when he jumps he beats the head in some kind of "invisible roof" near his head, and when I try to walking while he is jumping feels like slow motion gravity, like if it had decreased, the only way to make a jump right is if I release everything and jump and don't touch anything till he get to the ground.

    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     public Rigidbody2D rBody;
    4.     public Vector2 speed;
    5.     public Vector2 jumpStrength;
    6.     private Animator anim;
    7.     private bool isJumping;
    8.  
    9.     void Start ()
    10.     {
    11.         rBody = GetComponent<Rigidbody2D>();
    12.         anim = GetComponent<Animator>();
    13.     }
    14.    
    15.     void FixedUpdate ()
    16.     {
    17.         anim.SetBool ("isWalking", false);
    18.         if (Input.GetKey(KeyCode.RightArrow))
    19.         {
    20.             anim.SetBool("isWalking", true);
    21.             rBody.MovePosition(rBody.position + speed * Time.fixedDeltaTime);
    22.         }
    23.         if (Input.GetKey(KeyCode.LeftArrow))
    24.         {
    25.             rBody.MovePosition(rBody.position - speed * Time.fixedDeltaTime);
    26.             anim.SetBool("isWalking", true);
    27.         }
    28.         if (Input.GetKey(KeyCode.UpArrow) && !isJumping)
    29.         {
    30.             rBody.AddForce(jumpStrength);
    31.             isJumping = true;
    32.         }
    33.     }
    34.     void OnCollisionEnter2D(Collision2D coll)
    35.     {
    36.         if (coll.gameObject.tag == "Floor")
    37.         {
    38.             isJumping = false;
    39.         }
    40.     }
    41. }
    On Inspector:
    Gravity Scale: 3;
    Speed.X = 1, Speed.Y = 0;
    JumpStrength.X = 0, JumpStrength.Y = 300;

    Thanks;
    Arthur.
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    If you look at the documentation for Moveposition, you'll find this:
    "During the move, neither gravity or linear drag will affect the body. This causes the object to rapidly move from the existing position, through the world, to the specified position."

    So, your movement is cancelling out the gravity.

    Try using forces or adjust the x-component of the rigidbody's velocity instead.