Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Jumping question.

Discussion in 'Scripting' started by brunoenvia, Aug 25, 2021.

Thread Status:
Not open for further replies.
  1. brunoenvia

    brunoenvia

    Joined:
    Aug 5, 2019
    Posts:
    94
    i have a little issue in my script that i dont know how to solve it, i want to change the y variable so the player will jump making y gravity to positive, the thing is since both of jumping and movement methods are in update so the y value keeps changing constantly, and i dont know how i could change the y value, the y value is always negative...

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class PlayerMovement : MonoBehaviour
    7. {
    8.     public CharacterController playerController;  
    9.     public float gravity = -1f;
    10.     public float movementSpeed = 15f;
    11.     float x;
    12.     float y;  
    13.     float z;
    14.  
    15.     public Collider playerCollider;
    16.     public Rigidbody playerRb;  
    17.   //  private Vector3 movement;
    18.   public Vector3 playerVector;
    19.    
    20.     public float defaultSpeed = 15f;
    21.     public float jumpForce = 50f;
    22.     public bool isJumping = false;
    23.     public FixedJoystick joystickMove;
    24.     public Button jumpButton;
    25.  
    26.     public Transform gameCamera;
    27.  
    28.  
    29.     // raycast hit ground
    30.    
    31.     public bool isGrounded = false;
    32.     RaycastHit hitInfo;
    33.     RaycastHit slopeHit;
    34.     Vector3 raycastDirection;  
    35.     public LayerMask raycastLayers;
    36.     public float sphereRadius = 0.1f;  
    37.     public float castDistance = 0.01f;
    38.     public float slopeCastDistance = 1f;
    39.     public float slopeSpeed = 1f;  
    40.     Vector3 slopeMoveDirection;
    41.     Vector3 slopeJumpDirection;
    42.  
    43.     private void Awake()
    44.     {
    45.         playerController.detectCollisions = true;
    46.         raycastDirection = Vector3.down;
    47.         playerRb = GetComponent<Rigidbody>();
    48.         playerCollider = GetComponent<SphereCollider>();
    49.     }
    50.  
    51.     // Start is called before the first frame update
    52.     void Start()
    53.     {      
    54.        
    55.     }
    56.  
    57.      public void Movement()
    58.       {
    59.         x = joystickMove.Horizontal;
    60.         y = -gravity;
    61.         z = joystickMove.Vertical;
    62.  
    63.         playerVector = new Vector3(x, y, z); // the playervector input will have the x and z values. y is added later    
    64.        
    65.                
    66.  
    67.              
    68.        playerVector = playerVector * movementSpeed; // multiplies the playervector with the movementspeed variable;
    69.        playerController.Move(playerVector);
    70.  
    71.         Debug.Log(y);
    72.     }
    73.  
    74.     public void Jumping()
    75.     {
    76.         if (isJumping == false && IsGrounded() == true)
    77.         {
    78.             playerVector.y = gravity * Time.deltaTime;
    79.             isJumping = true;
    80.             Debug.Log("jump");
    81.         }
    82.  
    83.         /*  if (isJumping == false && IsGrounded() == true && OnSlope() == true)
    84.           {
    85.               slopeJumpDirection = Vector3.ProjectOnPlane(Vector3.up, slopeHit.normal); // detects the normal vector of the surface player is on
    86.               playerRb.AddForce(slopeJumpDirection * jumpForce, ForceMode.Impulse); // makes the player jump on the normal direction
    87.           } */
    88.     }
    89.  
    90.     // Update is called once per frame
    91.     void Update()
    92.     {
    93.        
    94.     }
    95.  
    96.     private void FixedUpdate()
    97.     {
    98.         Jumping();
    99.         Movement();      
    100.         IsGrounded();
    101.       //  OnSlope();
    102.  
    103.  
    104.  
    105.     }
    106.  
    107.  
    108.  
    109.  
    110.     private void MovementButtonRelease()
    111.     {
    112.         if (joystickMove.Horizontal == 0 && joystickMove.Vertical == 0) // se largar os botoes que mexem o player, a velocidade do rigidbody pára (o player pára de se mexer)
    113.         {
    114.  
    115.         }
    116.     }
    117.  
    118.  
    119.  
    120.    
    121.  
    122.    public bool IsGrounded() // cria uma funçao bool que verifica se o player está no chão ou não
    123.     {
    124.         if (Physics.SphereCast(playerCollider.bounds.center, sphereRadius, raycastDirection, out hitInfo, castDistance, raycastLayers))
    125.         {          
    126.  
    127.             if (hitInfo.collider.gameObject.layer == 7 || hitInfo.collider.gameObject.layer == 8) // se o layer do objeto que o raycast bateu for 7(Ground) então retorna um valor TRUE(significando que o play esta no chao)
    128.             {              
    129.                 Gizmos.color = Color.green;
    130.                 Debug.Log(hitInfo.collider);
    131.                 Debug.Log("TOUCHING GROUND!");              
    132.                 gameObject.transform.parent = null;
    133.                 isJumping = false;
    134.              
    135.                 return true;
    136.             }
    137.  
    138.             else if (hitInfo.collider.gameObject.layer == 6) // se o raycast colidir com o objeto cujo layer é igual a 6(movingPlatforms) o player vai ser child object do cubo que se mexe
    139.             {
    140.                 Gizmos.color = Color.green;
    141.                 Debug.Log(hitInfo.collider);
    142.                 Debug.Log("TOUCHING GROUND!");
    143.                 gameObject.transform.SetParent(hitInfo.collider.gameObject.transform, true);
    144.                 isJumping = false;
    145.              
    146.                 return true;
    147.             }
    148.  
    149.             else if (hitInfo.collider == null) // se o raycast nao detetar qualquer collider, o player nao está no chao
    150.             {
    151.                 Gizmos.color = Color.red;
    152.                 gameObject.transform.parent = null;
    153.                 isJumping = true;
    154.                
    155.                 return false;
    156.             }
    157.  
    158.             else // se o raycast nao detetar qualquer collider, o player nao está no chao
    159.             {
    160.                 gameObject.transform.parent = null;
    161.                 isJumping = true;
    162.                
    163.                 return false;
    164.             }
    165.         }
    166.  
    167.        
    168.         gameObject.transform.parent = null;
    169.         isJumping = true;
    170.         return false; // if the player isn't touching the ground he is jumping and not on any platform
    171.  
    172.  
    173.     }
    174.  
    175.     public bool OnSlope()
    176.     {
    177.  
    178.         if (Physics.Raycast(playerCollider.bounds.center, Vector3.down, out slopeHit, slopeCastDistance))
    179.         {
    180.             Debug.Log(slopeHit.normal);
    181.  
    182.             if (slopeHit.normal != Vector3.up)
    183.             {
    184.                
    185.                 slopeMoveDirection = Vector3.ProjectOnPlane(playerVector, slopeHit.normal);  // creates a vector3 that projects on plane surface from playerVector and hits on surface normal creating a perpendicular vector
    186.                 playerRb.AddForce(playerVector + slopeMoveDirection, ForceMode.Force); ; // the velocity will be the playervector + slopemovedirection, which means the vector will move in slope direction
    187.                 return true;
    188.             }
    189.  
    190.         }
    191.         return false;
    192.     }
    193.  
    194.  
    195.     private void OnDrawGizmosSelected()
    196.     {
    197.         Gizmos.color = Color.red;
    198.         Gizmos.DrawRay(playerCollider.bounds.center, Vector3.down * castDistance);
    199.         Gizmos.DrawSphere(playerCollider.bounds.center, sphereRadius);
    200.  
    201.         Gizmos.color = Color.yellow;
    202.         Gizmos.DrawRay(playerCollider.bounds.center, Vector3.down * slopeCastDistance);
    203.     }
    204.  
    205.     private void OnControllerColliderHit(ControllerColliderHit hit)
    206.     {
    207.         Debug.Log(hit);
    208.     }
    209.  
    210. }
     
  2. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Hello,
    Jump sets playerVector.y to -1, which is apparently called all the time,
    and Movement sets playerVector.y to 1 (-(-1)
    I get why you're getting inconsistent result.

    Why would you change gravity when your player jumps? Keep gravity as is and apply a positive upwards force bigger than gravity value when you want him to jump.
    If you change the gravity direction it would accelerate upwards forever.
    If you're not using any Physics engine, you'd need an acceleration vector and a velocity vector, I think. Now you have a rigidbody, you can safely use the engine's gravity and forces to achieve this without too much of a hassle. If you really want gravity to be 1, you can change it using
    Physics.gravity = new Vector3(0, -1.0F, 0);
     
  3. zombiegorilla

    zombiegorilla

    Moderator

    Joined:
    May 8, 2012
    Posts:
    8,968
    Do NOT delete the contents of posts, it makes the thread unreadable and is completely against the point of this forum. This forum exists as a support reference for everyone, not a just place to help you. The answers are here for future users benefit from the efforts that people kindly put into helping you. Deleting posts like this against the rules, rude to future users and rude to those who helped.



    The post has been reverted and thread closed.
     
    hippocoder likes this.
Thread Status:
Not open for further replies.