Home > Blockchain >  Pressing the space bar makes the console say NaN
Pressing the space bar makes the console say NaN

Time:04-20

I am making a script that allows the payer to move and jump. Moving with the WASD keys is fine but when I press the space bar to jump, but the console says NaN and the gravity in the game stops working I've looked at my player motor script and my input manager script, but I can't find any errors.

player motor script

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

public class PlayerMotor : MonoBehaviour
{
    private CharacterController controller;
    private Vector3 PlayerVelocity;
    private bool isGrounded;
    public float speed = 5f;
    public float gravity = -9.8f;
    public float jumpHeight = -3f;
    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        isGrounded = controller.isGrounded;
    }
    public void ProcessMove(Vector2 input)
    {
        Vector3 moveDirection = Vector3.zero;
        moveDirection.x = input.x;
        moveDirection.z = input.y;
        controller.Move(transform.TransformDirection(moveDirection) * speed * Time.deltaTime);
        PlayerVelocity.y  = gravity * Time.deltaTime;
        if (isGrounded && PlayerVelocity.y < 0)
            PlayerVelocity.y = -2f;
        controller.Move(PlayerVelocity * Time.deltaTime);
        Debug.Log(PlayerVelocity.y);
    }
    public void Jump()
    {
        if (isGrounded)
        {
            PlayerVelocity.y = Mathf.Sqrt(jumpHeight * -3.0f * gravity);
        }
    }
}

input manager script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class InputManager : MonoBehaviour
{
    private PlayerInput playerInput;
    private PlayerInput.OnFootActions onFoot;

    private PlayerMotor motor;
    // Start is called before the first frame update
    void Awake()
    {
        playerInput = new PlayerInput();
        onFoot = playerInput.OnFoot;
        motor = GetComponent<PlayerMotor>();
        onFoot.Jump.performed  = ctx => motor.Jump();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        // tell the playermotor to move using the value from our movement action
        motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
    }
    private void OnEnable()
    {
        onFoot.Enable();
    }
    private void OnDisable()
    {
        onFoot.Disable();
    }

}

CodePudding user response:

In this line it seems you are trying to get the square root of a negative number? PlayerVelocity.y = Mathf.Sqrt(jumpHeight * -3.0f * gravity);
Gravity and jumpheight are negative, multiplied with -3.0 that results in a negative number.
A quick test in Unity reveals that Mathf.Sqrt doesn't throw an error on negatives and instead returns NaN.

  • Related