Код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
[Header("Объекты")]
[SerializeField] public GameObject tower;
[SerializeField] public GameObject prefabBullet;
[Header("Параметры")]
[SerializeField] public float moveSpeed;
[SerializeField] public float rotateSpeed;
[SerializeField] public float towerSpeed;
[SerializeField] public float bulletSpeed;
[SerializeField] public float easyReloadTime;
[SerializeField] public float maxViewDistance;
bool ready = true;
RaycastHit2D raycast;
PlayerScript player;
private void Awake()
{
player = FindObjectOfType<PlayerScript>();
}
void Update()
{
//Move();
RotateTower();
Raycast();
}
void Move()
{
if (true)
{
transform.position += new Vector3(transform.up.x * moveSpeed * Time.deltaTime, transform.up.y * moveSpeed * Time.deltaTime, 0);
}
else if (true)
{
transform.position -= new Vector3(transform.up.x * moveSpeed * Time.deltaTime, transform.up.y * moveSpeed * Time.deltaTime, 0);
}
if (true)
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.eulerAngles.z + rotateSpeed * Time.deltaTime * 180);
tower.transform.rotation = Quaternion.Euler(0, 0, tower.transform.rotation.eulerAngles.z - rotateSpeed * Time.deltaTime);
}
else if (true)
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.eulerAngles.z - rotateSpeed * Time.deltaTime * 180);
tower.transform.rotation = Quaternion.Euler(0, 0, tower.transform.rotation.eulerAngles.z + rotateSpeed * Time.deltaTime);
}
}
void RotateTower()
{
tower.transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(player.transform.position.y - transform.position.y, player.transform.position.x - transform.position.x) * 180 / Mathf.PI - 90);
}
void Shoot()
{
if (ready)
{
GameObject clone = Instantiate(prefabBullet, tower.transform.position, tower.transform.rotation);
clone.AddComponent<BulletScript>();
clone.GetComponent<BulletScript>().speed = bulletSpeed;
clone.GetComponent<BulletScript>().type = false;
ready = false;
StartCoroutine(EasyReload());
}
}
IEnumerator EasyReload()
{
yield return new WaitForSeconds(easyReloadTime);
ready = true;
}
//Проблемный Участок Кода
void Raycast()
{
raycast = Physics2D.Raycast(new Vector3(transform.position.x + transform.up.x * 4, transform.position.y + transform.up.y * 4, transform.position.z), player.transform.position, maxViewDistance);
if (raycast)
{
if (raycast.collider.gameObject.tag == "Player")
{
Shoot();
}
}
}
}
Установленные Параметры: