- Home /
Trouble with raycast hitting a tagged object
I am trying to apply damage to an enemy(zombie) when it enters the attack range of a tower. Firstly I have set it up so the raycast works and only goes a certain amount of range, when the zombie enters the range, the tower looks at it. But now I am trying to kill the zombie.
Sorry if this code is sloppy, I haven't been doing this for long. As you can see in the function attack(), I am trying to make the ray detect what it is shooting with a tag, but the Debug.log is not showing up when it is in range.
 var distance;
 var targetTransform : Transform;
 var attackRange = 15.0;
 var moveSpeed = 5.0;
 var Damping = 6.0;
 var fireRate = 0.4;
 var allowedShot : boolean = true;
 var damage = 100;
 var hit : RaycastHit;
 
 function Start()
 {
 
     targetTransform = GameObject.FindWithTag("Zombie").transform;
 
 }
 
 function Update ()
 {
     
 
     
     
     
     distance = Vector3.Distance(targetTransform.position, transform.position);
     
     if (distance < attackRange)
     {
         
         attack();
     }
     
     if (distance > attackRange)
     {
         
     }
     
     Debug.DrawRay(transform.position, transform.forward * attackRange, Color.red);
     
     
     
 }
 
 function attack()
 {
     var rotation = Quaternion.LookRotation(targetTransform.position - transform.position);
     transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
     var forward : Vector3 = transform.TransformDirection(transform.forward);
     if (Physics.Raycast(transform.position, forward, hit, attackRange) && allowedShot)
     {
         if (hit.collider.gameObject.tag == "Zombie")
         {
             Debug.Log("zombie hit");
             //hit.transform.gameObject.SendMessage("ApplyDamage", 100, SendMessageOptions.DontRequireReceiver);
             allowedShot = false;
             reload();
         }
     }
 }
 
 function reload()
 {
     
     yield WaitForSeconds(fireRate);
     allowedShot = true;
 
 }
I have got it to work by removing the "if (hit.collider.gameObject.tag == "Zombie"" statement, but that is not what I want as the tower then begins to destroy anything in its path.
You are likely hitting something with your Raycast() you don't expect. Below line 50 insert:
 Debug.Log(hit.collider.name+","+hit.collider.tag);
Your answer
 
 
             Follow this Question
Related Questions
2D Collision 1 Answer
collision script to destroy 2 Answers
Raycast object as far as possible? 1 Answer
Move object to raycast point. 3 Answers
Capturing a point 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                