Search Unity

Adding jumps to grid movement character controller

Discussion in 'Scripting' started by thestrandedmoose, Feb 19, 2019.

  1. thestrandedmoose

    thestrandedmoose

    Joined:
    Jul 21, 2015
    Posts:
    70
    Hey guys- I have a character controller I built which only moves along the grid in Unity.

    It works great, but I can't seem to figure out how to get my character to jump and fall (in Y Axis) correctly. Does anyone have any recommendations for how I can achieve this?

    Code (CSharp):
    1.    
    2. private float unitLength = 2;
    3.  
    4.     private void FixedUpdate()
    5.     {
    6.         Move();
    7.     }
    8.  
    9.     void Move()
    10.     {
    11.         if (!Player.isDead && Player.gameStarted)
    12.         {
    13.             if ((increment < 1) && isMoving) { increment += speed / 1000; }
    14.             else { isMoving = false; }
    15.  
    16.             if (!isMoving || currentDirection == Vector3.zero)
    17.             {
    18.                 //Check if next direction is valid. If so, set to current direction
    19.                 if (CheckDirection(nextDirection))
    20.                 {
    21.                     currentDirection = nextDirection;
    22.                     RotatePlayer(currentDirection);
    23.                 }
    24.  
    25.                 //Check if current direction valid, set up movement for that direction and rotate player. Otherwise, stop (do nothing)
    26.                 if (CheckDirection(currentDirection))
    27.                 {
    28.                     increment = 0;
    29.                     isMoving = true;
    30.                     startPoint = transform.position;
    31.                     endPoint = transform.position + currentDirection;
    32.                 }
    33.                 else
    34.                 {
    35.                     RotatePlayer(nextDirection);
    36.                 }
    37.             }
    38.             else
    39.             {
    40.                 transform.position = Vector3.Lerp(startPoint, endPoint, increment);
    41.             }
    42.         }
    43.     }
    44.  
    45.  
    46.     public bool CheckDirection(Vector3 direction)
    47.     {
    48.         Vector3 targetPoint = transform.position + direction;
    49.         RaycastHit hit;
    50.         if(Physics.Linecast(transform.position, targetPoint, out hit))
    51.         {
    52.             Debug.DrawRay(transform.position, direction, Color.red);
    53.             if(hit.collider.tag == "Wall")
    54.             {
    55.                 return false;
    56.             }
    57.         }
    58.         return true;
    59.     }
    60.  
     
    Last edited: Feb 19, 2019