sphinx2001

EnemyController

May 11th, 2021
652
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class EnemyController : MonoBehaviour
  7. {
  8.     public Sprite[] sprites;
  9.     public int direction = 0; // 0 - вверх, 1 - вниз, 2 - влево, 3 - вправо.
  10.     public float speed = 0.05f;
  11.     private SpriteRenderer render;
  12.     private Vector2 step;
  13.     private Rect bgRect;
  14.     public GameObject bullet;
  15.     public float shotTimer = 3f;
  16.     public float shotSpeed = 3f;
  17.     public float moveTimer = 0;
  18.     public float maxMoveTimer = 1f;
  19.     private System.Random rnd;
  20.     public int rndSeed = 0;
  21.     void Start()
  22.     {
  23.         rnd = new System.Random(rndSeed);
  24.         render = GetComponent<SpriteRenderer>();
  25.         step = new Vector2();
  26.         GameObject bg = GameObject.FindGameObjectWithTag("Background");
  27.         Vector2 bg_pos = bg.transform.position;
  28.         Sprite bg_sprite = bg.GetComponent<SpriteRenderer>().sprite;
  29.         Camera cam = Camera.main;
  30.         Vector2 point1 = cam.ScreenToWorldPoint(bg_pos);
  31.         float w = -point1.x * 2;
  32.         float h = -point1.y * 2;
  33.         //point1.x = -point1.x;
  34.         bgRect = new Rect(point1.x, point1.y, w, h);
  35.  
  36.     }
  37.     void Update()
  38.     {        
  39.  
  40.         transform.rotation = Quaternion.identity;
  41.  
  42.         if (direction == 0)
  43.         {            
  44.             step = new Vector2(0, speed);
  45.         }
  46.         if (direction == 1)
  47.         {            
  48.             step = new Vector2(0, -speed);
  49.         }
  50.         if (direction == 2)
  51.         {            
  52.             step = new Vector2(-speed, 0);
  53.         }
  54.         if (direction == 3)
  55.         {            
  56.             step = new Vector2(speed, 0);
  57.         }
  58.        
  59.         render.sprite = sprites[direction];
  60.         Vector2 pos = gameObject.transform.position;
  61.         pos += step;
  62.         if (CheckMove(pos))
  63.         {
  64.             gameObject.transform.position = pos;
  65.         }
  66.         else
  67.         {
  68.             step = new Vector2();
  69.         }
  70.     }
  71.     bool CheckMove(Vector2 newPosition)
  72.     {
  73.         return bgRect.Contains(newPosition);
  74.     }
  75.     private void OnCollisionEnter2D(Collision2D collision)
  76.     {
  77.         //Debug.Log(collision);
  78.         if (collision.gameObject.tag == "Wall")
  79.         {
  80.             step = new Vector2();
  81.         }
  82.     }
  83. }
  84.  
RAW Paste Data