To start off, I know the least about Raycasts than any other function in unity. From what i have tried to pick up, they relay information of some type (i could be totally wrong)
I am following a tutorial for a shooting script, it involves a Raycast function that i think is not doing what it should, because I placed Debugs to single out the problem.
The Raycast function is on line 51. When i “shoot” the tag it gives me is of the terrain, and not of the player that is anywhere around me. This makes me think that forward is probably not the direction in front of me, and more of a global type command (i could be wrong again)
Is my code written correctly, to “shoot” a player right in front of me?
Here it is.
#pragma strict
var ableshoot = false;
var shooting = false;
var hit : RaycastHit;
var aeksound : AudioClip;
var walthersound : AudioClip;
var weaponnum : int;
var pbullets : int = 320;
var pbullets1 : int = 9;
var rbullets : int = 520;
var rbullets1 : int = 30;
var a = 1;
var nView : NetworkView;
function Start () {
nView = GetComponent(NetworkView);
if(nView.isMine)
Shoot();
}
function Update () {
weaponnum = gameObject.GetComponent(ChangeGun).weaponnum;
if(nView.isMine){
if(Input.GetMouseButtonDown(1))
Prepare();
if(Input.GetMouseButtonUp(1))
ableshoot = false;
if(Input.GetMouseButtonDown(0) && ableshoot == true)
shooting = true;
if(Input.GetMouseButtonUp(0))
shooting = false;
if(ableshoot == false){
shooting = false;
}
}
}
function Prepare(){
//yield WaitForSeconds();
ableshoot = true;
}
function Shoot(){
while(true){
if(shooting == true && weaponnum == 0 && rbullets1 > 0)
{
rbullets1--;
Physics.Raycast(transform.position,transform.forward,hit);
Debug.Log(hit.collider.tag);
//if(hit.transform !=null) // No need, all GO have Transform
//{
Debug.Log("HitPlayer");
Debug.Log(hit.collider.tag); // What is the tag it hits?
if(hit.collider.tag == "Player" || hit.collider.tag == "Vehicle")
{
Debug.Log("tagrecieved");
Network.Destroy(hit.transform.gameObject);
Debug.Log("Destroyed");
}
//}
GetComponent(AudioSource).PlayOneShot(aeksound, 1.0);
}
else if(weaponnum == 0 && rbullets1 == 0){
yield WaitForSeconds(2);
if(rbullets >= 30){
rbullets -= 30;
rbullets1 += 30;
}
else if(rbullets < 30){
rbullets1 += rbullets;
rbullets = 0;
}
}
if(shooting == true && weaponnum == 1 && pbullets1 > 0){
pbullets1--;
GetComponent(AudioSource).PlayOneShot(walthersound, 1.0);
Physics.Raycast(transform.position,transform.forward,hit);
Debug.Log(hit.collider.tag);
if(hit.transform !=null){
Debug.Log("HitPlayer");
if(hit.collider.tag == "Human" || hit.collider.tag == "Vehicle"){
Debug.Log("TagRecieved");
Network.Destroy(hit.transform.gameObject);
Debug.Log("Destroyed");
}
}
}
else if(weaponnum == 1 && pbullets1 == 0){
yield WaitForSeconds(2);
if(pbullets >= 30){
pbullets -= 30;
pbullets1 += 30;
}
else if(pbullets < 30){
pbullets1 += pbullets;
pbullets = 0;
}
}
if(weaponnum == 0)
yield WaitForSeconds(.075);
else if (weaponnum ==1)
yield WaitForSeconds(.5);
}
}