0
\$\begingroup\$

I have this script that I made for an FPS character.

public class Player_Movement : MonoBehaviour

{ public CharacterController controller; public Transform camera;

public float gravity = -9.81f;

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool grounded;

public GameObject joystick;
public bool isMoving;
public float speed = 12f;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;

public float jumpHeight;
public Vector3 yPosition;
public bool jumpAble = true;

// Update is called once per frame
void FixedUpdate()
{
    grounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if (grounded)
    {
        yPosition.y = -2f;
        jumpAble = true;
    }

    Vector3 direction = new Vector3(joystick.GetComponent<Joystick>().inputDirection.x, 0f, joystick.GetComponent<Joystick>().inputDirection.y);
    isMoving = direction.magnitude != 0 ? true : false;
    
    if (isMoving)
    {
        controller.Move(direction * speed * Time.deltaTime);
    }

    yPosition.y += gravity * Time.deltaTime;
    UnityEngine.Debug.Log(yPosition);
    controller.Move(yPosition * Time.deltaTime);
}

public Vector3 Jump()
 {
     UnityEngine.Debug.Log(jumpAble);
     UnityEngine.Debug.Log(grounded);
     if (jumpAble && grounded)
     {
         jumpAble = false;
         yPosition.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
         UnityEngine.Debug.Log(yPosition.y);
         UnityEngine.Debug.Log(yPosition);
         return yPosition;
     }

     return yPosition;
 }

}

The game operates on mobile touch controls, and the Jump() is called when the jump button is pressed. However, the character does not jump when I press the button, even though the function is being called, and the yPoisition is being changed in the function. I know that changing the yPosition should make the player jump, as when I add this code to the Update:

if (Input.GetKey(KeyCode.Space) && jumpAble)
         {
             fallDown.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
         }

Everything works fine. Why is the new yPoisition value not being passed to Update, and why is this happening?

\$\endgroup\$
2
  • \$\begingroup\$ why is your method returning the yPosition variable when you can access it from anywhere? As your code looks your fixedUpdate could set it to -2f, hard to say when we dont see what else happens around when Jump is called. And is there a benefit to reinvent the physics? \$\endgroup\$ Commented Nov 27, 2020 at 17:57
  • 1
    \$\begingroup\$ Is it possible that your ground check is returning true the frame after a jump, causing the code in FixedUpdate to change yPosition.y back to -2? \$\endgroup\$ Commented Nov 27, 2020 at 18:10

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.