Jumping question.

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…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController playerController;   
    public float gravity = -1f;
    public float movementSpeed = 15f;
    float x;
    float y;   
    float z;

    public Collider playerCollider;
    public Rigidbody playerRb;   
  //  private Vector3 movement;
  public Vector3 playerVector;
   
    public float defaultSpeed = 15f;
    public float jumpForce = 50f;
    public bool isJumping = false;
    public FixedJoystick joystickMove;
    public Button jumpButton;

    public Transform gameCamera;


    // raycast hit ground
   
    public bool isGrounded = false;
    RaycastHit hitInfo;
    RaycastHit slopeHit;
    Vector3 raycastDirection;   
    public LayerMask raycastLayers;
    public float sphereRadius = 0.1f;   
    public float castDistance = 0.01f;
    public float slopeCastDistance = 1f;
    public float slopeSpeed = 1f;   
    Vector3 slopeMoveDirection;
    Vector3 slopeJumpDirection;

    private void Awake()
    {
        playerController.detectCollisions = true;
        raycastDirection = Vector3.down;
        playerRb = GetComponent<Rigidbody>();
        playerCollider = GetComponent<SphereCollider>();
    }

    // Start is called before the first frame update
    void Start()
    {       
       
    }

     public void Movement()
      {
        x = joystickMove.Horizontal;
        y = -gravity;
        z = joystickMove.Vertical;

        playerVector = new Vector3(x, y, z); // the playervector input will have the x and z values. y is added later     
       
               

              
       playerVector = playerVector * movementSpeed; // multiplies the playervector with the movementspeed variable;
       playerController.Move(playerVector);

        Debug.Log(y);
    }

    public void Jumping()
    {
        if (isJumping == false && IsGrounded() == true)
        {
            playerVector.y = gravity * Time.deltaTime;
            isJumping = true;
            Debug.Log("jump");
        }

        /*  if (isJumping == false && IsGrounded() == true && OnSlope() == true)
          {
              slopeJumpDirection = Vector3.ProjectOnPlane(Vector3.up, slopeHit.normal); // detects the normal vector of the surface player is on
              playerRb.AddForce(slopeJumpDirection * jumpForce, ForceMode.Impulse); // makes the player jump on the normal direction
          } */
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    private void FixedUpdate()
    {
        Jumping();
        Movement();      
        IsGrounded();
      //  OnSlope();



    }




    private void MovementButtonRelease()
    {
        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)
        {

        }
    }



   

   public bool IsGrounded() // cria uma funçao bool que verifica se o player está no chão ou não
    {
        if (Physics.SphereCast(playerCollider.bounds.center, sphereRadius, raycastDirection, out hitInfo, castDistance, raycastLayers))
        {          

            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)
            {               
                Gizmos.color = Color.green;
                Debug.Log(hitInfo.collider);
                Debug.Log("TOUCHING GROUND!");               
                gameObject.transform.parent = null;
                isJumping = false;
              
                return true;
            }

            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
            {
                Gizmos.color = Color.green;
                Debug.Log(hitInfo.collider);
                Debug.Log("TOUCHING GROUND!");
                gameObject.transform.SetParent(hitInfo.collider.gameObject.transform, true);
                isJumping = false;
              
                return true;
            }

            else if (hitInfo.collider == null) // se o raycast nao detetar qualquer collider, o player nao está no chao
            {
                Gizmos.color = Color.red;
                gameObject.transform.parent = null;
                isJumping = true;
               
                return false;
            }

            else // se o raycast nao detetar qualquer collider, o player nao está no chao
            {
                gameObject.transform.parent = null;
                isJumping = true;
               
                return false;
            }
        }

       
        gameObject.transform.parent = null;
        isJumping = true;
        return false; // if the player isn't touching the ground he is jumping and not on any platform


    }

    public bool OnSlope()
    {

        if (Physics.Raycast(playerCollider.bounds.center, Vector3.down, out slopeHit, slopeCastDistance))
        {
            Debug.Log(slopeHit.normal);

            if (slopeHit.normal != Vector3.up)
            {
               
                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
                playerRb.AddForce(playerVector + slopeMoveDirection, ForceMode.Force); ; // the velocity will be the playervector + slopemovedirection, which means the vector will move in slope direction
                return true;
            }

        }
        return false;
    }


    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(playerCollider.bounds.center, Vector3.down * castDistance);
        Gizmos.DrawSphere(playerCollider.bounds.center, sphereRadius);

        Gizmos.color = Color.yellow;
        Gizmos.DrawRay(playerCollider.bounds.center, Vector3.down * slopeCastDistance);
    }

    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Debug.Log(hit);
    }

}

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);

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.

1 Like