Quantcast
Channel: Questions in topic: "enemy"
Viewing all articles
Browse latest Browse all 1488

[Solved]Chaining projectiles

$
0
0
Hi, I'm attempting to create a chaining effect for my projectile. The idea is that I want to shoot a projectile and when said projectile hits an enemy, I want it to find the closest enemy to the enemy I just hit and shoot a projectile in that direction. The way i've done it so far is something like this: When an enemy has been hit I make an array of all the enemies in the level. I loop through each one, except for the one I hit, and calculate the distance between them. The enemy with the shortest distance is assigned to a new enemy variable. I then instantiate my projectile, calculate a new direction vector between the new enemy and the enemy I previously hit, and add a force to that direction on the new projectiles rigidbody. The effect i'm getting is that the new projectile shoots off in the same direction as the original projectile the first time the enemy is hit. The second time the enemy's health drops to 0 and it dies, resulting in the new projectile simply standing still. Is there anything i've missed in my theory here? Here's some of my code of the effect: Notes: layer is used to make sure not to calculate distance with the enemy that was originally hit. The script is on the projectile private GameObject[] enemies; private GameObject newEnemy; private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Enemy") { Destroy(gameObject); other.gameObject.layer = 10; enemies = GameObject.FindGameObjectsWithTag("Enemy"); if (enemies.Length > 1) { for (int i = 0; i < enemies.Length; i++) { if (enemies[i].layer == 9) { distance = Vector3.Distance(other.transform.position, enemies[i].transform.position); if (distance < prevDist) { prevDist = distance; newEnemy = enemies[i]; } } } } var bullet = (GameObject)Instantiate(bulletPrefab, other.transform.position, other.transform.rotation); Physics.IgnoreCollision(bullet.GetComponent(), other); Vector3 dir = newEnemy.transform.position - other.transform.position; bullet.GetComponent().AddForce(dir * 6f); } other.gameObject.layer = 9; }

Viewing all articles
Browse latest Browse all 1488

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>