I have an enemy that when I get close to me he comes towards me and shoots me and when he gets to close he stops this is intended. Everything seems to be working fine but when he starts following and he stops he suddenly falls face down on the floor when he gets to close then as I walk away he gets back up. Also, when he follows and I back up away from him he falls and then gets back up when I get close to him.
My first time posting on unity forums so I’m unsure if this the correct place to post.
Below is my code.
using System.Collections;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting_Enemy : MonoBehaviour
{
private Transform _player;
private float _distance;
[SerializeField] private GameObject _EnemyBulletPrefab;
private GameObject _EnemyBullet;
private bool _alive;
private bool _playerInRange;
void Start()
{
_player = GameObject.Find("Player").transform;
_alive = true;
}
void Update()
{
CheckDistance();
if (_playerInRange)
AttackPlayer();
}
private void CheckDistance()
{
_distance = Vector3.Distance(this.transform.position, _player.transform.position);
if (_distance > 3 && _distance <= 10)
{
_playerInRange = true;
}
else
{
_playerInRange = false;
}
}
private void AttackPlayer()
{
//Turning enemy to look at player
transform.LookAt(_player);
transform.Translate(0, 0, Time.deltaTime);
//Shoot Player if enemy is still alive
if (_alive)
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.SphereCast(ray, 0.75f, out hit))
{
GameObject hitObject = hit.transform.gameObject;
if (hitObject.GetComponent<PlayerCharacter>())
{
if (_EnemyBullet == null)
{
_EnemyBullet = Instantiate(_EnemyBulletPrefab) as GameObject;
_EnemyBullet.transform.position = transform.TransformPoint(Vector3.forward * 1.5f);
_EnemyBullet.transform.rotation = transform.rotation;
}
}
}
}
}
}