- Home /
Target a single enemy
Hey guys what's up I'm making an FPS prototype for my game using raycasthit for the gun, but when I hit 1 enemy they all take damage. How do I maket it so that only the shooted enemy takes damage? Here's the script:
var force : float = 10;
var range : float = 200;
var clipnumb : int = 3;
var bulletsPerClip : int = 14;
var bulletsLeft : int;
var reloadTime : float = 1;
var shootAudio : AudioClip;
var reloadAudio : AudioClip;
var enemies : GameObject[];
var enemy : GameObject;
function Start () {
bulletsLeft = bulletsPerClip;
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
function Update () {
Shooting();
Reloading();
RayShoot();
}
function RayShoot (){
var hit : RaycastHit;
var directionRay = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, directionRay * range, Color.red);
if(Physics.Raycast(transform.position, directionRay, hit, range)){
for(var i : int = 0; i < enemies.length; i++){
var dir : Vector3 = (enemies[i].transform.position - transform.position).normalized;
var direction : float = Vector3.Dot(dir, transform.forward);
if(hit.collider.tag == "Enemy"){
if(direction > 0){
if(Input.GetButtonUp("Fire1") && bulletsLeft > 0){
enemy = enemies[i];
var eh : EnemyHealth = enemy.GetComponent("EnemyHealth");
eh.AdjustHealth(-10);
}
else{
}
}
}
}
}
}
function Shooting (){
if(Input.GetButtonUp("Fire1") && bulletsLeft){
bulletsLeft --;
if(bulletsLeft < 0){
bulletsLeft = 0;}
audio.PlayOneShot(shootAudio);
}
}
function Reloading (){
yield new WaitForSeconds(reloadTime);
if(Input.GetKeyUp(KeyCode.F)){
if(clipnumb > 0){
bulletsLeft = bulletsPerClip;
audio.PlayOneShot(reloadAudio);
}
clipnumb --;
}
}
Answer by Sisso · Feb 28, 2013 at 01:17 PM
Your logic here is a little mess. But the main problem is that you iterate over all enemies after got a raycast.
After rayscast, remove your enemies loop and do somehting like it:
hit.collider.gameObject.GetComponent(EnemyHealth).AdjustHealth(-10);
You're welcome. But what I did was simple read your logic. :P It is a really good exercise explain your code for for someone, an imaginary one, probably you will got the problem when you said "when raycast hit, for each enemy I will apply damage".
A gd exercise but one prob. I'm not a master of JS still have alot to learn.
Your answer
Follow this Question
Related Questions
How to Detect Collision, Calculate Velocity+Mass, Apply Damage 0 Answers
How to damage gameobject via raycast 1 Answer
Raycast script help? 1 Answer
Raycast Distance Help 1 Answer