A
A
Andrey2020-09-17 21:53:48
C++ / C#
Andrey, 2020-09-17 21:53:48

How to move to an object in Unity?

It is necessary that the "Herbivorous" object follows the static "Meal" object.

As I understand it, the coordinates are not read, and the object moves constantly to other coordinates. And constantly to the same.
It seems to be not difficult, everything is clear, but the following script does not work.

The code

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

public class pursuit : MonoBehaviour
{
    public Transform Target;
    public float Speed;
    [Tooltip("Как близко приближаться к Target")]
    public float RelaxDistance;
  float step = 0;
  void Start () {
    Update();
  }
    void Update()
    {
        var dir = Target.position - transform.position;
        if (dir.sqrMagnitude > RelaxDistance*RelaxDistance)
        {	
      Vector2 current_position = transform.position;
      Vector2 target_position = Target.position;
            step = Speed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(current_position, target_position, step);
            //transform.LookAt(Target);
        }
    }
}


Screenshots of objects and their movements.

5f63b0476b1fe426165917.png
5f63b0655fa7c160025831.png
5f63b08c389d7818616209.png
5f63b09431055016725123.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question