Скрипт движения объекта по траектории заданной положением других объектов. Может применяться для движения врагов, платформ или других игровых объектов.

    Настройка скрипта:

     

    результат работы скрипта:

     

    исходный код скрипта:

    using UnityEngine;
    using System.Collections;
    
    public class EnemyMove : MonoBehaviour 
    {
      [SerializeField] private float moveSpeed = 5f;	// скорость движения
      [SerializeField] private GameObject[] myWaypoints;	// список точек по которым будет двигаться енеми
      
      private int myWaypointId = 0;		                // текущая точка в массиве куда двигаться
      
      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      void EnemyMovement() 
      {
        // если точки есть
        if(myWaypoints.Length != 0) 
        {
          // если мы уже достигли назначенной точки, то переходим к следующей
          if(Vector3.Distance(myWaypoints[myWaypointId].transform.position, transform.position) <= 0) 
          {
            myWaypointId++;
          }
          
          //если точки исчерпаны то переходим к началу массива точек
          if(myWaypointId >= myWaypoints.Length) 
          {
            myWaypointId = 0;
          }
          
          //движемся в назначенную точку
          // move towards waypoint
          transform.position = Vector3.MoveTowards(transform.position, myWaypoints[myWaypointId].transform.position, moveSpeed * Time.deltaTime);
        }
      }
      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      // Update is called once per frame
      void Update () 
      {
        EnemyMovement();
      }
    }

     

     

    using UnityEngine;
    using System.Collections;
    
    public enum FadeDirection
    {
        In = -1,            // Fade In
        Out = 1             // Fade Out
    }
    
    //Затемнятор осветвлятор экрана
    public class FadeTransition : MyMonoBehaviour
    {
    
      [Header("Затемнятор осветвлятор экрана")] 
        [SerializeField] public float m_FadeTime = 0.5f;
    
    
        private int m_DrawDepth = -1000;
        private Texture2D m_FadeOutTexture;
        private FadeDirection m_FadeDirection = FadeDirection.In;
        private float m_CurrentAlphaColor = 1.0f;
        private float m_StartTime;
    
      //-----------------------------------------------------------------------------------------
      void Start()
      {
            m_FadeOutTexture = new Texture2D(2, 2);
    
            for (var mip = 0; mip < 2; ++mip)
            {
                for (var cols = 0; cols < 2; ++cols)
                {
                    m_FadeOutTexture.SetPixel(cols, mip, Color.black);
                }
            }
    
            m_FadeOutTexture.Apply();
      }
      //-----------------------------------------------------------------------------------------
      void OnGUI()
      {
        
        if (m_FadeDirection == FadeDirection.Out)
                m_CurrentAlphaColor = Mathf.Lerp(0.0f, 1.0f, ((Time.time - m_StartTime) / m_FadeTime));
            else
                m_CurrentAlphaColor = Mathf.Lerp(1.0f, 0.0f, ((Time.time - m_StartTime) / m_FadeTime));
    
            GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, m_CurrentAlphaColor);
            GUI.depth = m_DrawDepth;
            GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), m_FadeOutTexture);
    
      
      }
      //-----------------------------------------------------------------------------------------
      public float BeginFade(FadeDirection fadeDirection)
      {
            m_StartTime = Time.time;
            m_FadeDirection = fadeDirection;
            return m_FadeTime;
      }    
        
      //-----------------------------------------------------------------------------------------
      public void FadeIn()
      {
        BeginFade(FadeDirection.In);
      }
      //-----------------------------------------------------------------------------------------
      public void FadeOut()
      {
        BeginFade(FadeDirection.Out);
      }
      //-----------------------------------------------------------------------------------------
      public void FadeInverse()
      {
        if(m_FadeDirection==FadeDirection.In)
        { 
          BeginFade(FadeDirection.Out);
          return;
        }
    
        if(m_FadeDirection==FadeDirection.Out)
        {
          BeginFade(FadeDirection.In);
          return;
        }
      }
    
    }

    Эффект бегущей строки.

    в стиле ZX-Spectrum

    chronos horizontal moiving text

     

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    //скроллит текст горизонтально, посимвольно
    
    public class HorizontalMovedTextChar : MyMonoBehaviour 
    {
      //--------------------------------
      [Header("Состояние объекта изначально")]
      [SerializeField] private bool GameObjectSetActive	= true;
    
      [Header("Событие по которому строка начнёт движение")]
      [SerializeField] 	private GameEvents EventOnStart = GameEvents.nil;
    
      [Header("Событие которое сгенерируется по окончанию")]
      [SerializeField] 	private GameEvents GenerateEventOnEnd = GameEvents.nil;
      //--------------------------------
      private Text   text_component;
      private string text_original;
      private string text;
      //--------------------------------
    
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      void Start () 
      {
        text_component = this.GetComponent<Text>();
        text_original = text_component.text;
        if(EventOnStart 	!= GameEvents.nil) globalEManager.StartListening(EventOnStart, StartMoving);
        else StartMoving();
    
        gameObject.SetActive(GameObjectSetActive);
      }
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      public void StartMoving()
      {
        gameObject.SetActive(true);
        text = text_original;
        InvokeRepeating("MovingText",0,0.15f);
      }
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      private void MovingText () 
      {
        //Debug.Log("HorizontalMovedTextChar : text.Length = " + text.Length);
        //21 именно как и ниже, чила там и тут должны быть одинаковыми
        if(text.Length<=21)
        {
          if(DebugLog==true) Debug.Log("HorizontalMovedTextChar : Cancel Invoka" );
          CancelInvoke();
          globalEManager.TriggerEvent(GenerateEventOnEnd,gameObject);
          gameObject.SetActive(GameObjectSetActive);
          return;
        }
    
        text =  text.Remove(0,1);
    
        text_component.text = InsertColor(text);
        //text = text.Remove(0,1);
    
        //Debug.Log("HorizontalMovedTextChar : text=" + text);
      }
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      private string InsertColor(string s)
      {
        //21 именно как и выше, чила там и тут должны быть одинаковыми
        s = s.Insert(21,"</color>");
        s = s.Insert(20,"<color=black>");
    
        s = s.Insert(20,"</color>");
        s = s.Insert(19,"<color=red>");
    
        s = s.Insert(19,"</color>");
        s = s.Insert(18,"<color=blue>");
    
        s = s.Insert(18,"</color>");
        s = s.Insert(17,"<color=magenta>");
    
        s = s.Insert(17,"</color>");
        s = s.Insert(16,"<color=green>");
    
        s = s.Insert(16,"</color>");
        s = s.Insert(15,"<color=cyan>");
    
        s = s.Insert(15,"</color>");
        s = s.Insert(14,"<color=yellow>");
    
    
        s = s.Insert(6,"</color>");
        s = s.Insert(5,"<color=yellow>");
    
        s = s.Insert(5,"</color>");
        s = s.Insert(4,"<color=cyan>");
    
        s = s.Insert(4,"</color>");
        s = s.Insert(3,"<color=green>");
    
        s = s.Insert(3,"</color>");
        s = s.Insert(2,"<color=magenta>");
    
        s = s.Insert(2,"</color>");
        s = s.Insert(1,"<color=blue>");
    
        s = s.Insert(1,"</color>");
        s = s.Insert(0,"<color=red>");
    
        return s;
      }
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      void OnDisable()
      {
        CancelInvoke();
      }
      //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    }

    Эффект патрулирования объекта по заданной траектории, хорошо подойдёт так же для перемещающихся платформ или врагов.

    Настройки в инспекторе:

    Пример настройки в окне редактора:

     

    Результат работы:

     

    код скрипта:

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class PatrolBehaviour : MonoBehaviour 
    {
    
        public enum eMode
        {
            None,       
            Loop,
            PingPong
        }
      [Header("Shift-добавить точку \tCtrl-удалить точку\n")]
        /// <summary>
        /// List of all path nodes
        /// </summary>
        public List<Vector2> Path = new List<Vector2>();a
    
        /// <summary>
        /// Wrap mode for platform movement
        /// </summary>
        public eMode WrapMode; 
    
        /// <summary>
        /// Time to way in a node before moving to the next one
        /// </summary>
        public float WaitingTime = 1f;
    
        /// <summary>
        /// Time to go from a path node to the next one
        /// </summary>
        public float MovingTime = 1f;
        
        /// <summary>
        /// Base position of all path nodes
        /// </summary>
        public Vector3 BasePos;
    
        private float m_curMovTime;
        private float m_waitingTime;
        private int m_pathIdx = 0;
        private bool m_pingPongForward = true;
        private Vector3 m_prevPos;
    
        void Reset()
        {
            Path.Add( Vector2.one );
            Path.Add( Vector2.zero );
        }
    
        void Start()
        {
            BasePos = transform.position;
            m_pathIdx = Path.Count - 1;
        }
    
        void FixedUpdate()
        {
            if( Path != null && Path.Count > 0 )
            {
                if (m_waitingTime > 0f)
                {
                    m_waitingTime -= Time.deltaTime;
                }
                else
                {
                    m_pathIdx = (Path.Count + m_pathIdx) % Path.Count;
                    if (m_curMovTime == 0f)
                    {
                        m_prevPos = transform.position;
                    }
                    m_curMovTime += Time.deltaTime;
                    Vector3 vTarget = (Vector3)Path[m_pathIdx] + BasePos;
                    vTarget.z = transform.position.z;
                    if (m_curMovTime < MovingTime)
                    {
                        transform.position = Vector3.Lerp(m_prevPos, vTarget, m_curMovTime / MovingTime);
                    }
                    else
                    {
                        // Position reached
                        transform.position = vTarget;
    
                        if (WrapMode == eMode.Loop)
                        {
                            m_curMovTime = 0f;
                            m_waitingTime = WaitingTime;
                            --m_pathIdx;
                        }
                        else if (WrapMode == eMode.PingPong)
                        {
                            m_curMovTime = 0f;
                            m_waitingTime = WaitingTime;
                            m_pingPongForward = m_pingPongForward? m_pathIdx != 0 : m_pathIdx == (Path.Count - 1);
                            if (m_pingPongForward)
                            {
                                --m_pathIdx;
                            }
                            else
                            {
                                ++m_pathIdx;
                            }
                        }
                    }
                }
            }
        }
    }
     ​
     

    Страница 1 из 2

    © 2021 MidaDev by Dimusikus.

    Please publish modules in offcanvas position.