Search Unity

Jumping NavMeshAgent

Discussion in 'Navigation' started by Volosnya, Nov 16, 2017.

  1. Volosnya

    Volosnya

    Joined:
    Nov 16, 2017
    Posts:
    1
    Sorry for my english.
    I need to my character with NavMeshAgent on it move towards the target, and when i press "Space" character will jump and continued to move towards the target.



    i tried to use this code but after i am press "Space" my characrer stops moving, and if i press space several times, character flies up and stops moving towards the target, and only when he falls down he continues to move towards the target.

    private NavMeshAgent agent;
    public LayerMask groundMask;
    private Rigidbody rb;

    public Transform target;
    public float jumpForce;
    public float groundRadius;
    public bool isGrounded;
    public Collider[] ground;


    void Start()
    {
    agent = GetComponent<NavMeshAgent>();

    agent.autoBraking = false;

    agent.destination = target.position;

    rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
    ground = Physics.OverlapSphere(transform.position, groundRadius, groundMask);

    if (ground.Length == 0)
    {
    isGrounded = false;
    agent.enabled = false;
    }
    else{
    isGrounded = true;
    agent.enabled = true;
    agent.destination = target.position;
    }

    if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
    Jump();

    }

    void Jump()
    {
    isGrounded = false;

    agent.enabled = false;

    rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    agent.velocity = rb.velocity;
    }
    Target.png