Search Unity

Player auto jumps on a slope for some reason

Discussion in '2D' started by davy421, Aug 21, 2016.

  1. davy421

    davy421

    Joined:
    Sep 4, 2015
    Posts:
    14
    When the player starts moving down on a slope, for some reason he jumps initially, even though the jump button wasn't pressed, but then runs as intended when it lands again, like this:



    And when the player moves up on a slope, for some reason it jumps when it stops, even though the jump button was not pressed, like this:



    The main problem is that the characters jumps for some reason.

    It's not really an issue that the character doesn't have the same rotation like the slope when it lands on it or that the character is sliding down a bit when standing still on it, but resolving these couple of things would be a nice addition as well.

    Also, I'm moving the character not by applying force, but by:

    Code (CSharp):
    1. myRigidbody.velocity = new Vector2 (Input.GetAxisRaw ("Horizontal") * movementSpeed, myRigidbody.velocity.y);
    SOLVED! Posted the solution below.
     
    Last edited: Aug 24, 2016
  2. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    438
    Would it be fixed if you apply force instead? Because i see Input used i assume the code is in Update() and not FixedUpdate()? I would think that all direct modifications of physics, such as velocity should be done inside FixedUpdate().
     
  3. davy421

    davy421

    Joined:
    Sep 4, 2015
    Posts:
    14
    That is a good assumption, but in this case, I only used Input here in the example for simplicity's sake, but I actually run that code in the FixedUpdate() and I get the Horizontal Axis Raw in the Update() and save it to a variable so I can later use it in the FixedUpdate().
     
  4. davy421

    davy421

    Joined:
    Sep 4, 2015
    Posts:
    14
    I was able to find a solution:

    This keeps the character moving along the platform up and down by accordingly setting X and Y velocities:

    Code (CSharp):
    1. if (onTiltedSurface) {
    2.       float x = Mathf.Cos (Mathf.Deg2Rad * slopeAngle) * movementSpeed * horizontal;
    3.       float y = Mathf.Sin (Mathf.Deg2Rad * slopeAngle) * movementSpeed * horizontal;
    4.       myRigidbody.velocity = new Vector2 (x, y);
    5. }
    Also it seems that gravity skews these calculations a bit so when I enter collision with an tilted object I do:

    Code (CSharp):
    1. myRigidbody.gravityScale = 0;
    And on collision exit I do:

    Code (CSharp):
    1. myRigidbody.gravityScale = 1;
     
    Last edited: Aug 24, 2016