Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Need help getting an animal to move to food

Discussion in 'Navigation' started by jkuehlin, Oct 25, 2019.

  1. jkuehlin

    jkuehlin

    Joined:
    Sep 8, 2017
    Posts:
    5
    I'm not sure what the best way to do this is. I would like to the elephant to locate then move to the watermelon and eat it, but I'm having problems getting him there.

    Screen Shot 2019-10-25 at 12.51.05 AM.png

    Here's my code... I have two different ways of doing it and neither are idea. Could I get some suggestions please? Thank you!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class elephantscript : MonoBehaviour
    6. {
    7.     GameObject target;
    8.  
    9.     private Animator animator;
    10.     private bool isEating = false;
    11.     public int MoveSpeed = 1;
    12.     private Vector3 targetPos;
    13.  
    14.  
    15.     void Start()
    16.     {
    17.         animator = GetComponent<Animator>();
    18.  
    19.         target = GameObject.Find("Watermelon");
    20.         targetPos = target.transform.position;
    21.     }
    22.  
    23.  
    24.     void Update()
    25.     {
    26.         if (Input.GetKeyDown(KeyCode.Space) && !isEating)
    27.         {
    28.             animator.SetBool("isEating", true);
    29.             isEating = true;
    30.         }
    31.         else if (Input.GetKeyDown(KeyCode.Space) && isEating)
    32.         {
    33.             animator.SetBool("isEating", false);
    34.             isEating = false;
    35.         }
    36.  
    37.  
    38.         Vector3 targetPosition = new Vector3(
    39.             target.transform.position.x,
    40.             transform.position.y,
    41.             target.transform.position.z);
    42.  
    43.         transform.LookAt(targetPosition);
    44.  
    45.         //transform.position += transform.forward * MoveSpeed * Time.deltaTime;
    46.         transform.position = Vector3.MoveTowards(transform.position, targetPos, 1);
    47.     }
    48. }
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    381
    This is exactly the kind of thing the NavMesh system is for.
    Read up on it here.
     
  3. jkuehlin

    jkuehlin

    Joined:
    Sep 8, 2017
    Posts:
    5
    Thank you captain obvious.
     
  4. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    381
    Well, your question sounds as if you didn't take the time to read it through. You're not using the NavMesh system at all, if your code snippet is to be believed. You're simply moving its position in a straight line using basic vector math here.
    Read up on the NavMesh system. If you still have questions after that, come back to this forum with those specific questions in mind.