Bullet Shoot At Enemy Position

Hello Everyone

i use this FireScript :

						fireRate = fireRate - extrafirerate;
			nextFire = Time.time + fireRate;
			launchPosition = cameraHeadTransform.TransformPoint(0, 0, 0);	
			GameObject go = Instantiate(blaster, launchPosition,  Quaternion.Euler(cameraHeadTransform.eulerAngles.x + 90,
			                                                    transform.eulerAngles.y, 0)) as GameObject;

and in The Blaster[Bullet] prefab Added BlasterScript

	myTransform.Translate(Vector3.up * 100 * Time.deltaTime);
		
	Destroy(gameObject,1.5f);

The cameraHeadTransform = SpawnPoint its inside the player

i just want : When I Shoot, the bullet Go To Closest[Distance] Enemy With Tag “Enemy”

1 Answer

1

// find all enemies
GameObject enemies = GameObject.FindGameObjectsWithTag (“Enemy”);

//this will find the closest enemy to your launchPosition
int closestIndex = 0;
float closestDistance = Mathf.Infinity;
float tempDistance;
for (int i = 0; i < enemies.Length; i++) {
    tempDistance = Vector3.Distance (launchPosition, enemies*.transform.position);*

if (tempDistance < closestDistance) {
closestDistance = tempDistance;
closestIndex = i;
}
}
GameObject closestEnemy = enemies[closestIndex];

//this is your bullets direction
Vector3 bulletDirection = closestEnemy.transform.position-launchPosition;

//instantiate your bullet with this rotation.
Quaternion bulletRotation = Quaternion.LookRotation(bulletDirection, Vector3.up);

Thanks but not working :) I dont know, its just spawn the bullet very far away and under the ground .. hold on second ,, i should attack the script to the bullet or inside my firescipt anyway i tried both. i guess he got problem in finding the Tag

Sorry, I didn't write it to work if you copied and pasted it directly into your code. I edited it, hopefully you can get it to work now. But your bullet is going to go up, unless you change your bullet to move Vector3.forward instead of Vector3.up

Its Works Like Charm,, thank you but there is little problem that he aiming on the leg.. i fixed it by adding vector3 Vector3 bulletDirection = closestEnemy.transform.position-launchPosition+ new Vector3(0,1,0); its works but i'm not sure if its right way xD thx again

Good I'm glad it worked, and sorry about the typo. Its hard writing code on a phone haha