Raycast gun

I started trying to make a raycust gun script when I realised that I have no idea what to do.

var enemy : GameObject
function Update () 
{
    var fwd = transform.TransformDirection (Vector3.forward);
    if (Physics.Raycast (transform.position, fwd, 50)) 
	{
        
    }
}

I was thinking that I could go from here somewhere, like giving the enemy lives and making clicking while being hit by a raycast remove 1 life. But I am new to raycasting, and could use some help.

Okay doky, Lets have a look:

So for your gun, I’m guessing you want to shoot every time you press the Fire1 button? (Left Mouse)

125

125 // - damage of your gun, sent to your enemy - \
var damage : float = 1;

function Update(){
   if(Input.GetButtonDown("Fire1")){
      FireOneShot();
    }
}

function FireOneShot(){
   var direction = transform.TransformDirection(Vector3.forward);
   var hit : RaycastHit;

   if (Physics.Raycast (localOffset, direction, hit, 300)) {
   Debug.DrawLine (localOffset, hit.point, Color.cyan);

   // - send damage to object we hit - \\
   hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}125

So apply this script to your gun object.

Then, for your enemy, you need a damage receiver:

var hitPoints = 10.0

function ApplyDamage(damage : float){
   if(hitPoints <= 0.0
   return

   hitPoints -= damage;
   if(hitPoints <= 0.0){
      Invoke("DelayedDetonate",0);
   }
} 

function DelayedDetonate(){
   Destroy(gameObject);
}

Hope that helps - I haven’t tested that so it might be buggy. If you come across any problems then let me know125

You can check what the Raycast hits with RaycastHit and seclude with the corresponding tag for the object it hits, for instance:

function Update () {
  if(shooting){
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, Vector3.forward, hit)) {
      if(hit.collider.tag=="Enemy"){
        enemy.life--;
      }
    }
  }
}

(Code not tested)