Hi I’m trying to add speed to projectile when target is too close projectile speed decrease drastically. When it is far there is no problem but when it’s too close this happening
public class Mp5 : MonoBehaviour
{
private GameObject[] target;
public GameObject projectile;
AudioSource source;
public AudioClip mp5sound;
float range = 2f;
Vector3 direction;
float time = 1f;
float getTime;
Vector2 next;
float nextv;
Vector2 closest;
float closestv=Mathf.Infinity;
GameObject closeste;
bool timeb;
void Start()
{
source = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
timer();
if(timeb)
{
timeb = false;
getTime = time;
turn();
shoot();
}
}
void turn()
{
float x = Input.GetAxis("Horizontal");
if (x < 0) transform.localScale = new Vector3(-1, 1, 1);
else if (x > 0) transform.localScale = new Vector3(1, 1, 1);
direction = closestEnemy().transform.position - transform.position;
Mathf.Atan2(direction.y, direction.x);
direction.Normalize();
Quaternion rotation = Quaternion.LookRotation(direction);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
}
void shoot()
{
if (direction.magnitude <= range)
{
source.PlayOneShot(mp5sound);
GameObject bullet = Instantiate(projectile, transform.position, transform.rotation);
bullet.GetComponent<Rigidbody2D>().velocity=(direction * 3000f * Time.deltaTime);
}
}
void timer()
{
if (!timeb)
{
getTime -= Time.deltaTime;
}
if (getTime <= 0) timeb = true;
}
GameObject closestEnemy()
{
GameObject cloesest=null;
float cloesestdist = Mathf.Infinity;
target = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject t in target)
{
float nextv = Vector2.Distance(t.transform.position, transform.position);
nextv = Mathf.Abs(nextv);
if (nextv < cloesestdist)
{
cloesest = t;
cloesestdist = nextv;
}
}
return cloesest;
}
}