Advertisement
OwlyOwl

Code_sample_cats_patrol

May 17th, 2020
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. [RequireComponent(typeof(Rigidbody2D), typeof(Animator))]
  6. public class Patrol : MonoBehaviour
  7. {
  8.     public float speed;
  9.     private float waitTime;
  10.     public float startWaitTime;
  11.  
  12.     public Transform[] moveSpots;
  13.  
  14.     private int currentSpot = 0;
  15.  
  16.     private SpriteRenderer _sr;
  17.     private Animator _animator;
  18.     private Rigidbody2D _rb;
  19.     private static readonly int Move = Animator.StringToHash("move");
  20.     private static readonly int Disable1 = Animator.StringToHash("disable");
  21.  
  22.     private AudioSource _as;
  23.    
  24.     void Start()
  25.     {
  26.         waitTime = startWaitTime;
  27.         _sr = GetComponent<SpriteRenderer>();
  28.         _rb = GetComponent<Rigidbody2D>();
  29.         _animator = GetComponent<Animator>();
  30.         _as = GetComponent<AudioSource>();
  31.         _as.Play();
  32.         _animator.SetBool(Move, true);
  33.     }
  34.  
  35.     void Update()
  36.     {
  37.         var newPosition =
  38.             Vector2.MoveTowards(transform.position, moveSpots[currentSpot].position, speed * Time.deltaTime);
  39.         var shift = newPosition - (Vector2)transform.position;
  40.         var scale = transform.localScale;
  41.         scale.x = Mathf.Sign(shift.x);
  42.         transform.localScale = scale;
  43.        
  44.         _rb.MovePosition(newPosition);
  45.         if (Vector2.Distance(transform.position, moveSpots[currentSpot].position) < 0.01f)
  46.         {
  47.             if (waitTime <= 0)
  48.             {
  49.                 currentSpot = (currentSpot + 1) % moveSpots.Length;
  50.                 waitTime = startWaitTime;
  51.                 if (!_as.isPlaying)
  52.                     _as.Play();
  53.                 _animator.SetBool(Move, true);
  54.             }
  55.             else
  56.             {
  57.                 waitTime -= Time.deltaTime;
  58.                 if (_as.isPlaying)
  59.                     _as.Stop();
  60.                 _animator.SetBool(Move, false);
  61.             }
  62.  
  63.             return;
  64.         }
  65.     }
  66.  
  67.     public void Disable()
  68.     {
  69.         _animator.SetTrigger(Disable1);  
  70.         Debug.Log($"Enemy {gameObject.name} disabled");
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement