Search Unity

Make a character jump in the same direction of a moving platform.

Discussion in 'Physics' started by seen360, Oct 11, 2018.

  1. seen360

    seen360

    Joined:
    Aug 8, 2018
    Posts:
    2
    I am making a game similar to Beat Stomper on Android and IOS. I Have a character that sits on a moving platform. When I Jump I want him to jump up but also a little bit in the direction the platform was moving in. For example the platform is moving right and the character jumps up and to the right rather than straight up. Right now the character parents itself to the platform to stick on to it. When It jumps, It goes straight up in the air. I am not sure what the best way to do this is. I tried to make a script that finds the direction the platform is going in.Then apply torque in the direction the platform is going.

    Is there a better way to accomplish this?

    Code (CSharp):
    1.  void FixedUpdate()
    2.     {
    3.        
    4.         var velocity = (transform.position - lastPos);
    5.         lastPos = transform.position;
    6.         if (velocity.x > 0)
    7.         {
    8.             dir = -1;
    9.             Debug.Log(" we are going right");
    10.         }
    11.         if (velocity.x < 0)
    12.         {
    13.             dir = 1;
    14.             Debug.Log(" we are going left");
    15.         }
    16.  
    17.         if (Input.GetKeyDown("space") && isGrounded)
    18.         {
    19.             isGrounded = false;
    20.             //rb.AddForce(jump * jumpForce, ForceMode2D.Impulse);
    21.             rb.AddTorque(jumpForce * dir,ForceMode2D.Impulse);
    22.            
    23.         }
     
    Last edited: Oct 11, 2018
  2. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    467
    You can separate the horizontal and vertical movement:

    Code (CSharp):
    1. rb.AddForce(jumpForce * Vector2.up + velocity * Vector2.right,ForceMode2D.Impulse);
    Does that work?
     
  3. seen360

    seen360

    Joined:
    Aug 8, 2018
    Posts:
    2
    That code makes the character jump up in a straight line rather than to the direction of the platform
     
  4. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    467
    Alright, can you make sure
    velocity
    actually has the intended value? So if you're platform is moving at a horizontal speed of 2.5 units per second, what is the velocity vector exactly? Also, I didn't read your code well enough: Since velocity already is a vector, the code should actually be
    Code (CSharp):
    1. rb.AddForce(jumpForce * Vector2.up + velocity, ForceMode2D.Impulse);
    But I assume the problem is in your velocity calculation. You need to divide by the time step:
    var velocity = (transform.position - lastPos) / Time.fixedDeltaTime


    You probably ended up with a velocity value that was way to small to have a noticeable effect.

    I hope that works!