12/31/16

Shooting in Unity3D js

A little Script in JS to shooting weapons


Gun

var gun : GameObject; //your weapon
var shotsite : GameObject; //site of instantiate the bullet
var bullet : GameObject; //bullet to shoot
var cantBullet : int; // amount of bullets
var maxCantBullet : int; //maximun amount of bullets for municion
var municion : int; //amount of municion

private var timeS : float; //time intermediate for shooting
var timeSM : float; //Maximun time for shoot 

function Update(){

    shoot();

}

 function shoot(){

    if(timeS>0){
         timeS -= Time.deltaTime;
    }else{
        if(Input.GetButtonDown("Fire1")){
            if(cantBullet > 0){
                shootB();
                timeS = timeSM;
            }else{ //if not have munition in the charger
                 if(municion > 0){ //if have more chargers, recargate gun
                      cantBullet = maxCantBullet;
                      municion--;
                 }
            }
        }
    }

   if(Input.GetKeyDown("r")){ //to recharge ammo
     if(municion > 0){
            cantBullet = maxCantBullet;
            municion--;
     }
   }

 }

function shootB(){

    Instantiate(bullet, shotsite.transform.position, shotsite.transform.rotation);

}


Bullet

private var r : Rigidbody; //the bullet need a rigidbody and a collider trigger
var speed: float;
var particle : GameObject;

function Start () {

r = GetComponent.<Rigidbody>();

}

function Update () {

r.MovePosition(transform.position + transform.forward * speed* Time.deltaTime);


}

function OnTriggerEnter(other : Collider){

if(other.tag == "enviroment"){
               Instantiate(particle, transform.position, transform.rotation);
               Destroy(this.gameObject);
}

}


That is all n_n

No comments:

Post a Comment