Почему враг стреляет даже тогда когда расстояние больше 1f в Vector3.Distance(_player.position, transform.position) < 1f

Рейтинг: 0Ответов: 1Опубликовано: 25.08.2023
 public Transform _player;
 public float _speed = 1f;
 public static float hp = 3;

 public GameObject _bull;
 public Transform _firePoint;
 public float _fireSpeed = 100f;
 public float _fireTime = 2f;
 private float _nextTime = 0f;
 void Start()
 {
    _player = transform;
 }

 void Update()
 {
    Vector3 dir = _player.position - transform.position;
    if (Time.time > _nextTime && Vector3.Distance(_player.position, transform.position) 
 < 1f)
    {
        _nextTime = Time.time + _fireTime;
        shot();
    }
    if (hp <= 0)
    {
        Destroy(gameObject);
    }
    }
    void shot() 
    {
    GameObject bullet = Instantiate(_bull, _firePoint.position, _firePoint.rotation);
    Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    rb.velocity = -_firePoint.right * _fireSpeed;
    }

Ответы

▲ 0Принят

У Вас расстояние всегда равно 0. В методе Start() вы присваиваете _player = transform; Соответственно выражение Distance(_player.position, transform.position) тождественно Distance(transform.position, transform.position). Совет на будущее: когда сталкиваетесь со сложностями, добавляйте логи. Это поможет отследить, почему срабатывает (или не срабатывает) то или иное условие.