Search Unity

Need help to keep momentum while jumping

Discussion in '2D' started by Spaymp, May 30, 2020.

  1. Spaymp

    Spaymp

    Joined:
    May 29, 2020
    Posts:
    1
    I'm making an endless runner in which you chase a bus, so I need to keep the same distance between the player and the bus, but the jumping kills the momentum and eventually the bus gets away.
    Any suggestions?
    Here's the script for the player:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.     public float moveSpeed;
    7.     public float jumpForce;
    8.  
    9.     private Rigidbody2D myRigidbody;
    10.  
    11.  
    12.     public bool grounded;
    13.     public LayerMask whatIsGround;
    14.  
    15.     private Collider2D myCollider;
    16.  
    17.     private Animator myAnimator;
    18.  
    19.  
    20.  
    21.     // Start is called before the first frame update
    22.     void Start()
    23.     {
    24.         myRigidbody = GetComponent<Rigidbody2D>();
    25.      
    26.         myCollider = GetComponent<Collider2D>();
    27.  
    28.         myAnimator = GetComponent<Animator>();
    29.  
    30.     }
    31.  
    32.     // Update is called once per frame
    33.     void Update()
    34.     {
    35.  
    36.         grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);
    37.        
    38.        
    39.        
    40.         // Movment
    41.         myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
    42.  
    43.         if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
    44.         {
    45.  
    46.  
    47.             if (grounded)
    48.             {
    49.  
    50.  
    51.                 myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
    52.             }
    53.  
    54.  
    55.  
    56.  
    57.         }
    58.  
    59.         myAnimator.SetFloat ("Speed", myRigidbody.velocity.x);
    60.         myAnimator.SetBool ("Grounded", grounded);
    61.  
    62.  
    63.     }
    64. }
    65.  

    Script for the bus:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class BusMovement : MonoBehaviour
    4. {
    5.     public float moveSpeed;
    6.    
    7.     private Rigidbody2D myRigidbody2;
    8.  
    9.  
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         myRigidbody2 = GetComponent<Rigidbody2D>();
    15.  
    16.  
    17.  
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.       myRigidbody2.velocity = new Vector2(moveSpeed, myRigidbody2.velocity.y);
    24.        
    25.  
    26.  
    27.     }
    28. }
    29.  
    Thanks : )