Search Unity

How to jump when key pressed. Edit code

Discussion in 'Scripting' started by Kaperosa, Feb 14, 2018.

  1. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
    Currently the model is jumping continuously by itself. I'm wanting my model to only jump when I press the space bar. I paid for this script so I'm wondering on how to edit it properly.
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5.  
    6. [RequireComponent (typeof(Collider))]
    7. public class JumpPhysics : MonoBehaviour
    8. {
    9.     public bool showDebugRays = false; // debug flag to show the Raycasts used for collision detection
    10.  
    11.     public float jumpPower = 5.0f;
    12.     public float gravity = -.1f;
    13.  
    14.     public bool allowVariableJumpHeight = false;
    15.     public float holdJumpUpwardSpeed = 5.0f; // speed at which object moves up towards max
    16.     public float holdJumpMaxHeight = 10.0f;  // max hold jump height before applying gravity
    17.     private float initialYPosition = 0;      // initial y position used to calculate at if at max
    18.  
    19.     // double jump flag and vars similar to variable jump height
    20.     public bool allowDoubleJump = false;
    21.     public float doubleJumpPower = 5.0f;
    22.     public float doubleJumpUpwardSpeed = 5.0f;
    23.     public float doubleJumpMaxHeight = 10.0f;
    24.  
    25.     // holds name of Layer that belongs to player so we can ignore during raycast
    26.     public string playerLayerName;
    27.  
    28.     // lists that hold tags and layers object can collide with that affect jump
    29.     public List<string> collidingTagList;
    30.     public LayerMask collidingLayerMask;
    31.  
    32.     // amount ray extends beyond collider
    33.     public float collisionRayDepthUp = .01f;
    34.     public float collisionRayDepthDown = .01f;
    35.  
    36.     // offset each ray to the left/right before casting up/down to match character
    37.     public Vector3 collisionRayLeftOffset = new Vector3(-.2f, 0, 0);
    38.     public Vector3 collisionRayRightOffset = new Vector3(.2f, 0, 0);
    39.  
    40.     private float currentGravity = 0;
    41.     private Vector2 moveDirection = Vector2.zero;
    42.     private Vector2 jumpDirection = Vector2.zero;
    43.     public bool IsGrounded { get; private set; }
    44.     public bool IsHoldingJump { get; private set; }
    45.     public bool InAir { get; private set; }
    46.     public bool IsMaxHeightReached { get; private set; }
    47.     public bool IsDoubleJumping { get; private set; }
    48.     public bool HasDoubleJumped { get; private set; }
    49.     public bool HasJumpedOnce { get; private set; }
    50.  
    51.     void Awake()
    52.     {
    53.         IsGrounded = false;
    54.         IsHoldingJump = false;
    55.         InAir = false;
    56.      
    57.         // if playerLayerName blank, default to 'Ignore Raycast'
    58.         if (gameObject.layer == 0)
    59.             gameObject.layer = 2;
    60.     }
    61.  
    62.     void Update()
    63.     {
    64.         // check collision with ground
    65.         if (RaycastCollideVertical(Vector3.down)) {
    66.             IsGrounded = true;
    67.             IsMaxHeightReached = false;
    68.             HasDoubleJumped = false;
    69.             IsDoubleJumping = false;
    70.             HasJumpedOnce = false;
    71.             InAir = false;
    72.             currentGravity = 0;
    73.             jumpDirection = Vector2.zero;
    74.             initialYPosition = transform.position.y;
    75.         }
    76.         // else we're not grounded (probably falling off ledge)
    77.         else if (!InAir) {
    78.             InAir = true;
    79.             IsGrounded = false;
    80.             IsHoldingJump = false;
    81.             currentGravity = gravity;
    82.         }
    83.      
    84.         // perform physics update
    85.         CalculateMoveDirection();
    86.  
    87.         // move via transform component
    88.         transform.Translate(moveDirection * Time.deltaTime);
    89.  
    90.         // draw the rays for collisions with environment
    91.         if (showDebugRays)
    92.             DebugRays();
    93.     }
    94.  
    95.     bool JumpInputCheck()
    96.     {
    97.         // button press
    98.         return Input.GetButtonDown("Jump");
    99.     }
    100.  
    101.     bool RemovedJumpInputCheck()
    102.     {
    103.         // let go of button
    104.         return Input.GetButtonUp("Jump");
    105.     }
    106.  
    107.     Vector2 GetJumpPowerVector()
    108.     {
    109.         return (HasDoubleJumped) ? new Vector2(0, doubleJumpPower) : new Vector2(0, jumpPower);
    110.     }
    111.     void CalculateMoveDirection()
    112.     {
    113.         moveDirection = Vector2.zero;
    114.  
    115.         // checks: double jump allowed, hasn't double jumped yet, has jumped once, and jump button pushed
    116.         // sets: is double jumping this frame, resets jump key hold, jump velocity, initial Y position
    117.         if (allowDoubleJump && !HasDoubleJumped && HasJumpedOnce && JumpInputCheck()) {
    118.             IsDoubleJumping = true;
    119.             IsHoldingJump = false;
    120.             jumpDirection = Vector2.zero;
    121.             initialYPosition = transform.position.y;
    122.         }
    123.  
    124.         // checks: on ground or double jumping this frame, jump button pushed, and not hitting ceiling
    125.         if (!IsHoldingJump && (IsGrounded || (allowDoubleJump && IsDoubleJumping && !HasDoubleJumped)) && JumpInputCheck() && !RaycastCollideVertical(Vector3.up)) {
    126.             IsHoldingJump = true;
    127.             InAir = true;
    128.             IsGrounded = false;
    129.             currentGravity = gravity;
    130.          
    131.             // needed for double jump check
    132.             HasJumpedOnce = true;
    133.             if (IsDoubleJumping)
    134.                 HasDoubleJumped = true;
    135.  
    136.             // if variable jump height allowed, start us moving at variable jump height speed else regular jump (or second jump of double jump)
    137.             jumpDirection = (allowVariableJumpHeight) ? new Vector2(0, holdJumpUpwardSpeed) : GetJumpPowerVector();
    138.             IsMaxHeightReached = false;
    139.         }
    140.      
    141.         // let go of jump button
    142.         if (RemovedJumpInputCheck()) {
    143.             IsHoldingJump = false;
    144.         }
    145.  
    146.         // if airborne, apply gravity to current jump speed then add to movement vector
    147.         if (InAir) {
    148.  
    149.             // check if we're at max height from variable jump height or hitting ceiling so we can apply gravity
    150.             if (RaycastCollideVertical(Vector3.up) || (allowVariableJumpHeight && AtMaxVariableJumpHeight())) {
    151.                 IsMaxHeightReached = true;
    152.             }
    153.  
    154.             // if hit ceiling, stop all upward movement.
    155.             if (RaycastCollideVertical(Vector2.up)) {
    156.                 jumpDirection = (jumpDirection.y > 0) ? new Vector2(0, 0) : jumpDirection;
    157.             }
    158.  
    159.             // apply gravity if normal jump or if allowing variable jump height, at max variable jump height or released button
    160.             if (!allowVariableJumpHeight || (allowVariableJumpHeight && (IsMaxHeightReached || !IsHoldingJump)))
    161.                 jumpDirection += new Vector2(0, currentGravity);
    162.  
    163.             // moveDirection holds final value of movement delta
    164.             moveDirection += jumpDirection;
    165.         }
    166.     }
    167.  
    168.     bool AtMaxVariableJumpHeight()
    169.     {
    170.         // true if while holding jump, our current y position is equal or over the initial y position before jump
    171.         // if double jump enabled, we use seperate max heights.
    172.         if (allowDoubleJump && IsDoubleJumping)
    173.             return (transform.position.y - initialYPosition) >= doubleJumpMaxHeight;
    174.         else
    175.             return (transform.position.y - initialYPosition) >= holdJumpMaxHeight;
    176.     }
    177.  
    178.     bool RaycastCollideVertical(Vector3 direction)
    179.     {
    180.         // creating rays to cast, 1 for each side of object
    181.         Ray floorRay_L = new Ray(transform.position + collisionRayLeftOffset, direction);
    182.         Ray floorRay_R = new Ray(transform.position + collisionRayRightOffset, direction);
    183.  
    184.         // which way and how deep should we cast
    185.         float directionSign = (direction == Vector3.up) ? 1 : -1;
    186.         float directionDepth = (direction == Vector3.up) ? collisionRayDepthUp : collisionRayDepthDown;
    187.  
    188.         RaycastHit hit;
    189.         // hit on left side
    190.         if (Physics.Raycast(floorRay_L, out hit, this.GetComponent<Collider>().bounds.extents.y + directionDepth, collidingLayerMask)) {
    191.             // we hit explicit tagged object
    192.             if (HitTagOrLayerObject(hit.collider.gameObject)) {
    193.                 // set our position to hit point so we don't stutter in place
    194.                 transform.position = new Vector3(transform.position.x, hit.point.y + (-directionSign * this.GetComponent<Collider>().bounds.extents.y), transform.position.z);
    195.                 return true;
    196.             }
    197.         }
    198.  
    199.         // hit on right side
    200.         if (Physics.Raycast(floorRay_R, out hit, this.GetComponent<Collider>().bounds.extents.y + directionDepth, collidingLayerMask)) {
    201.             // we hit explicit tagged object
    202.             if (HitTagOrLayerObject(hit.collider.gameObject)) {
    203.                 // set our position to hit point so we don't stutter in place
    204.                 transform.position = new Vector3(transform.position.x, hit.point.y + (-directionSign * this.GetComponent<Collider>().bounds.extents.y), transform.position.z);
    205.                 return true;
    206.             }
    207.         }
    208.         // no hit
    209.         return false;
    210.     }
    211.     bool HitTagOrLayerObject(GameObject collisionObject)
    212.     {
    213.         // check if we are colliding by tag
    214.         if (collidingTagList.Count > 0) {
    215.             foreach (string tag in collidingTagList) {
    216.                 if (collisionObject.CompareTag(tag))
    217.                     return true;
    218.             }
    219.             return false;
    220.         }
    221.  
    222.         return true;
    223.     }
    224.  
    225.     // draws all rays in up and down direction
    226.     void DebugRays()
    227.     {
    228.         Ray dfloorRay_L = new Ray(transform.position + collisionRayLeftOffset, Vector3.down);
    229.         Ray dfloorRay_R = new Ray(transform.position + collisionRayRightOffset, Vector3.down);
    230.         Ray ufloorRay_L = new Ray(transform.position + collisionRayLeftOffset, Vector3.up);
    231.         Ray ufloorRay_R = new Ray(transform.position + collisionRayRightOffset, Vector3.up);
    232.  
    233.         Debug.DrawLine(dfloorRay_L.origin, dfloorRay_L.origin - new Vector3(0, this.GetComponent<Collider>().bounds.extents.y + collisionRayDepthUp, 0), Color.magenta);
    234.         Debug.DrawLine(dfloorRay_R.origin, dfloorRay_R.origin - new Vector3(0, this.GetComponent<Collider>().bounds.extents.y + collisionRayDepthUp, 0), Color.magenta);
    235.         Debug.DrawLine(ufloorRay_L.origin, ufloorRay_L.origin + new Vector3(0, this.GetComponent<Collider>().bounds.extents.y + collisionRayDepthDown, 0), Color.red);
    236.         Debug.DrawLine(ufloorRay_R.origin, ufloorRay_R.origin + new Vector3(0, this.GetComponent<Collider>().bounds.extents.y + collisionRayDepthDown, 0), Color.red);
    237.     }
    238. }
     
    Last edited: Feb 14, 2018
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
  3. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If you open that link / thread, you will see it explained there.
     
  5. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
    I got it now, thank you. How would I change the code to only make my character jump when I press the space bar?
     
    Last edited: Feb 14, 2018
  6. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343
    Change these two methods:
    Code (CSharp):
    1. bool JumpInputCheck()
    2. {
    3.     // button press
    4.     return Input.GetKeyDown(KeyCode.Space);
    5. }
    6.  
    7. bool RemovedJumpInputCheck()
    8. {
    9.     // let go of button
    10.     return Input.GetKeyUp(KeyCode.Space);
    11. }
    EDIT: Oh it is jumping continuously? So this probably will not fix it.
     
    Last edited: Feb 14, 2018
  7. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
    It does make it jump higher on commend but it's still jumping continuously.
     
  8. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    well the default key in the input manager for jump is space... so that's entirely redundant.

    generally if you pay for some code they're not usually happy for you redistributing that code for free....


    code looks fine, have you populated the list in the inspector from lines 29 and 30.
     
  9. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343
    Yeah, I misunderstood the question and was editing my post.
     
  10. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
    Ah I diddn't think about that, thank you for letting me know. I have done so.