Skip to content

Instantly share code, notes, and snippets.

@SamatKadyrov
Created August 11, 2024 11:32
Show Gist options
  • Select an option

  • Save SamatKadyrov/2f441c33e4eccd86c3d9ce432e65603c to your computer and use it in GitHub Desktop.

Select an option

Save SamatKadyrov/2f441c33e4eccd86c3d9ce432e65603c to your computer and use it in GitHub Desktop.
using System.Collections;
using UnityEngine;
public class MoveAlongPath : MonoBehaviour
{
public Transform[] points; // Массив точек, по которым будет двигаться объект
public float speed = 2f; // Скорость движения
private int currentPointIndex = 0; // Индекс текущей точки
private void Update()
{
// Проверяем, есть ли точки для движения
if (points.Length == 0 || currentPointIndex >= points.Length) return;
// Получаем целевую точку
Transform targetPoint = points[currentPointIndex];
// Двигаем объект к целевой точке
float step = speed * Time.deltaTime; // Скорость движения с учётом времени
transform.position = Vector3.MoveTowards(transform.position, targetPoint.position, step);
// Проверяем, достиг ли объект целевой точки
if (Vector3.Distance(transform.position, targetPoint.position) < 0.1f)
{
currentPointIndex++; // Переходим к следующей точке
// Если достигли последней точки, останавливаем движение
if (currentPointIndex >= points.Length)
{
currentPointIndex = points.Length; // Устанавливаем индекс на максимальное значение, чтобы остановиться
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment