Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question NavMesh on/off for jumping problem.

Discussion in 'Scripting' started by Cheap_Shampoo, Nov 22, 2023.

  1. Cheap_Shampoo

    Cheap_Shampoo

    Joined:
    Sep 25, 2023
    Posts:
    3
    Please someone help me get out of this!

    I've tried so many different ways to solve this. I just want a slime to jump at the player's location. If i disable navmesh it jumps in place, if I enable navmesh it chases the player. I Can't seem to get it to just jump at the player while attacking, or any state at all.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class SlimeAI : MonoBehaviour
    7. {
    8.     public NavMeshAgent agent;
    9.     public Transform player;
    10.     public LayerMask whatIsGround, whatIsPlayer;
    11.  
    12.     //Patroling
    13.     public Vector3 walkPoint;
    14.     bool walkPointSet;
    15.     public float walkPointRange;
    16.     //Attacking
    17.     public float timeBetweenAttacks;
    18.     bool alreadyAttacked;
    19.     //States
    20.     public float sightRange, attackRange;
    21.     public bool playerInSightRange, playerInAttackRange;
    22.  
    23.     public float KnockbackForce = 1;
    24.     public int Damage;
    25.  
    26.  
    27.     public Collider Weapon;
    28.     public Collider Slime;
    29.     public Collider PlayerCollider;
    30.     public GameObject Player;
    31.     public GameObject SlimeObject;
    32.     public Animator animator;
    33.     public Rigidbody RB;
    34.  
    35.     [Range(0.1f, 100.0f)]
    36.     public float moveSpeed = 1.0f;
    37.     [Range(1.0f, 250.0f)]
    38.     public float jumpStrength = 10.0f;
    39.     [Range(0, 100)]
    40.     public int inAirPaneltyPercentage = 90;
    41.  
    42.     [Range(0.1f, 10.0f)]
    43.     public float gravity = 1.0f;
    44.  
    45.     [Range(0.1f, 50.0f)]
    46.     public float maxGravity = 10.0f;
    47.     private float verticalVelocity = 1.0f;
    48.     private Vector3 move = Vector3.zero;
    49.  
    50.  
    51.     public float fallMultiplier = 2.5f;
    52.     public float lowJumpMultiplier = 2f;
    53.  
    54.     public Transform groundPoint;
    55.     public Transform SlimeTransform;
    56.     public bool isGrounded;
    57.  
    58.  
    59.     // Start is called before the first frame update
    60.     void Start()
    61.     {
    62.        
    63.         bool alive = true;
    64.         if (Weapon == null)
    65.         {
    66.             Debug.LogWarning("No Weapon");
    67.         }
    68.  
    69.     }
    70.  
    71.     // Update is called once per frame
    72.     void Update()
    73.     {
    74.         ApplyGravity();
    75.         //Check for sight and attack range
    76.         playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
    77.         playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
    78.  
    79.  
    80.  
    81.         if (!playerInSightRange && !playerInAttackRange) Patroling();
    82.         if (playerInSightRange && !playerInAttackRange) ChasePlayer();
    83.         if (playerInAttackRange && playerInSightRange) AttackPlayer();
    84.  
    85.         var Health = SlimeObject.GetComponent<Health>();
    86.  
    87.         if (Health.currentHealth <= 0)
    88.         {
    89.             animator.SetBool("alive", false);
    90.         }
    91.  
    92.  
    93.  
    94.         RaycastHit hit;
    95.         if (Physics.Raycast(SlimeTransform.position, Vector3.down, out hit, 0.65f, whatIsGround))
    96.         {
    97.             isGrounded = true;
    98.         }
    99.         else
    100.         {
    101.             isGrounded = false;
    102.         }
    103.  
    104.         if (isGrounded == true)
    105.         {
    106.             NavEnable();
    107.            // RB.velocity = Vector3.zero;
    108.         }
    109.        
    110.     }
    111.  
    112.     private void Awake()
    113.     {
    114.         RB = GetComponent<Rigidbody>();
    115.         player = GameObject.Find("Player").transform;
    116.         agent = GetComponent <NavMeshAgent>();
    117.     }
    118.  
    119.     private void Patroling()
    120.     {
    121.         //if (isGrounded == true)
    122.        // {
    123.  
    124.             if (!walkPointSet) SearchWalkPoint();
    125.  
    126.             if (walkPointSet)
    127.                 agent.SetDestination(walkPoint);
    128.  
    129.             Vector3 distanceToWalkPoint = transform.position - walkPoint;
    130.             ApplyJumpSlime();
    131.  
    132.             //Walkpoint reached
    133.             if (distanceToWalkPoint.magnitude < 1f)
    134.                 walkPointSet = false;
    135.        // }
    136.  
    137.     }
    138.     private void SearchWalkPoint()
    139.     {
    140.         //Calculate random point in range
    141.         float randomZ = Random.Range(-walkPointRange, walkPointRange);
    142.         float randomX = Random.Range(-walkPointRange, walkPointRange);
    143.  
    144.         walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
    145.  
    146.         if (Physics.Raycast(walkPoint, -transform.up, 1f, whatIsGround))
    147.             walkPointSet = true;
    148.     }
    149.     private void ChasePlayer()
    150.     {
    151.  
    152.         if (isGrounded)
    153.         {
    154.             agent.SetDestination(player.position);
    155.  
    156.             ApplyJumpSlime();
    157.         }
    158.  
    159.     }
    160.     private void AttackPlayer()
    161.     {
    162.         //Make sure enemy doesnt't move
    163.         if (isGrounded)
    164.           {
    165.         agent.SetDestination(player.position);
    166.  
    167.  
    168.  
    169.         //transform.LookAt(player);
    170.  
    171.         if (!alreadyAttacked)
    172.             {
    173.             ///Attack code here
    174.             ///BULLETS OR SPAWN OBJECTS the instantiate them
    175.             ApplyJumpSlime();
    176.  
    177.  
    178.  
    179.             alreadyAttacked = true;
    180.             Invoke(nameof(ResetAttack), timeBetweenAttacks);
    181.  
    182.             }
    183.             }
    184.  
    185.     }
    186.  
    187.     private void ResetAttack()
    188.     {
    189.         alreadyAttacked = false;
    190.     }
    191.  
    192.     private void ApplyJumpSlime()
    193.     {
    194.         //StartCoroutine(Jump);
    195.         if (isGrounded)
    196.         {
    197.             isGrounded = false;
    198.             //NavDisable();
    199.             RB.AddForce(0, 4, 0);
    200.             //WaitForSeconds(1);
    201.             //RB.AddForce(0, -4, 0);
    202.             //verticalVelocity += Mathf.Sqrt(jumpStrength * 2.0f * gravity);
    203.             //move.y = verticalVelocity;
    204.             //ApplyGravity();
    205.             //Vector3 direction = Slime.transform.position - transform.position;
    206.             //direction.Normalize();
    207.             //direction.y = 10;
    208.             //isGrounded = true;
    209.         }
    210.     }
    211.  
    212.     void NavEnable()
    213.     {
    214.         agent.enabled = true;
    215.         //RB.isKinematic = true;
    216.         //agent.updatePosition = true;
    217.         //agent.updateRotation = true;
    218.         agent.isStopped = false;
    219.     }
    220.  
    221.     void NavDisable()
    222.     {
    223.         agent.enabled = false;
    224.         //RB.isKinematic = false;
    225.         //agent.updatePosition = false;
    226.         //agent.updateRotation = false;
    227.         agent.isStopped = true;
    228.     }
    229.  
    230.     private void ApplyGravity()
    231.     {
    232.         if (isGrounded)
    233.         {
    234.             verticalVelocity = 0.0f;
    235.         }
    236.  
    237.         verticalVelocity -= Mathf.Sqrt(gravity * Time.fixedDeltaTime);
    238.         verticalVelocity = Mathf.Clamp(verticalVelocity, -maxGravity, float.MaxValue);
    239.  
    240.         move.y = verticalVelocity;
    241.     }
    242.  
    243.  
    244.     void Die()
    245.     {
    246.         Destroy(gameObject);
    247.     }
    248.  
    249.  
    250. //void OnCollisionEnter(Collider other)
    251. /// </summary>
    252. /// <param name="other"></param>
    253.     //{
    254.     //    if (other.gameObject.tag == "Ground")
    255.     //    {
    256.     //        //NavEnable();
    257.     //        //isGrounded = true;
    258.     //    }
    259.     //}
    260.  
    261.      void OnTriggerEnter(Collider other)
    262.     {
    263.         if (other.gameObject.tag == "weapon")
    264.         {
    265.             //Weapon Damage
    266.             animator.SetTrigger("hit");
    267.             var WeaponAttack = Player.GetComponent<WeaponController>();
    268.             var WeaponDamage = WeaponAttack.WeaponDamage;
    269.             print("Hit With Weapon");
    270.             var Health = SlimeObject.GetComponent<Health>();
    271.             Health.currentHealth -= WeaponDamage;
    272.  
    273.         }
    274.         if (other.gameObject.tag == "Player")
    275.         {
    276.             //Player Damage and KnockBack
    277.             print("Collided with Player");
    278.             Vector3 hitDirection = other.transform.position - transform.position;
    279.             hitDirection = hitDirection.normalized;
    280.             var Health = Player.GetComponent<Health>();
    281.             Health.HurtPlayer(Damage, hitDirection);
    282.         }
    283.     }
    284.  
    285.  
    286.  
    287.  
    288. }
    289.  
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    757
    Disable the agent before making it jump using something like this:
    Code (CSharp):
    1. RB.AddForce(((player.transform.position-transform.position).normalized*20)+Vector3.up*30);
     
    Last edited: Nov 22, 2023
  3. Cheap_Shampoo

    Cheap_Shampoo

    Joined:
    Sep 25, 2023
    Posts:
    3
    OOOh awesome lol. That was what I was looking for! I've been trying forever to achieve this at least. Can you help me fine tune it a little? I changed the 20 to 1, and 30 to 3 since its small scale. My question is, how can I completely stop movement while its grounded? Then do a jump at the player while airborne? RB.velocity = Vector3.zero is just making it slow down and get stuck. I am super grateful for that piece of code!
     
  4. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    757
    After making it jump you can wait for its velocity to drop and then enable the agent again.
    Code (CSharp):
    1.     if (jumping && RB.velocity.magnitude<2)
    2.     {
    3.         jumping=false;
    4.         RB.isKinematic=true; // set RB.isKinematic=false when jumping
    5.         agent.enabled=true;
    6.     }
    If after jumping you feel it's taking too long to come to a stop then you can try increasing its friction and drag setting.
     
  5. Cheap_Shampoo

    Cheap_Shampoo

    Joined:
    Sep 25, 2023
    Posts:
    3
    nevermind thanks for the help.
     
    Last edited: Dec 2, 2023