fr0stn1k

Unity3(Task3)_Kovylov

Mar 8th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using UnityEngine;
  3.  
  4. public class ToPointAndBack : MonoBehaviour
  5. {
  6.     private Vector3 _startVector3;
  7.     public Vector3 _targetVector3 = new Vector3(0, 1, 0);
  8.     private Vector3 _movingVector3;
  9.     public float speed = 1;
  10.     private float _path;
  11.  
  12.     void Start()
  13.     {
  14.         // Сохранение изначальной позиции в стартовый вектор
  15.         _startVector3 = transform.position;
  16.         //Сохранение вектора Б в вектор движения
  17.         _movingVector3 = _targetVector3;
  18.     }
  19.  
  20.     // Update is called once per frame
  21.     void Update ()
  22.     {
  23.         // Переменная содержащая путь (Скорость * deltaTime)
  24.         _path = speed * Time.deltaTime;
  25.  
  26.         // Вызов функции движения
  27.         MoveToPoint();
  28.  
  29.         // Проверка достижения точки вектора Б и назначение целью вектор А
  30.         if (isReachedPoint(_targetVector3))
  31.             _movingVector3 = _startVector3;
  32.  
  33.         // Проверка достижения точки вектора А и назначение целью вектор Б
  34.         if (isReachedPoint(_startVector3))
  35.             _movingVector3 = _targetVector3;
  36.        
  37.     }
  38.  
  39.     // Проверка достижения координат с некоторой погрешностью из-за использования transform.Translate
  40.     private bool isReachedPoint(Vector3 vector3)
  41.     {
  42.         return Math.Abs(transform.position.x - vector3.x) <= 0.1f
  43.                && Math.Abs(transform.position.y - vector3.y) <= 0.1f
  44.                && Math.Abs(transform.position.z - vector3.z) <= 0.1f;
  45.  
  46.     }
  47.  
  48.     // Фукнция запускающая перемещение объекта, использующий вектор промежуточного хранения направления _movingVector3
  49.     private void MoveToPoint()
  50.     {
  51.         transform.Translate((_movingVector3 - transform.position).normalized * _path);
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment