- Home /
How do I create a raycast from the end of my gun to go wherever i have my gun pointed
I have a raycast script and i want to make it so that the ray gets casted from the end of my gun, so that when i click my mouse button the ray is created at the end of my gun and travel foward wherever my gun is pointed.
Here is my script: var endBarrel :Transform; var sound : AudioClip;
var TheDamage = 100;
var Effect : Transform;
var Enemy : GameObject[];
function Start() {
}
function Update(){
var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));
if (Physics.Raycast (ray, hit, 100)) {
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
if(Input.GetButtonDown("Fire1")){
// you can use PlayOneShot to specify the sound...
audio.PlayOneShot(sound);
audio.Play();
}
if (Input.GetMouseButtonDown(0)){
if (Physics.Raycast (endBarrel.position, transform.forward, 100))
{
}
}
}
Line 39 looks like it does what you need. What problems are you having?
It casts the ray to the center of the screen i want it so that it comes out the end of my gun
Answer by Em3rgency · Jun 26, 2013 at 08:49 PM
Try:
var endBarrel :Transform;
var sound : AudioClip;
var TheDamage = 100;
var Effect : Transform;
var Enemy : GameObject[];
function Start()
{
}
function Update()
{
var hit : RaycastHit;
if(Input.GetButtonDown("Fire1"))
{
// you can use PlayOneShot to specify the sound...
audio.PlayOneShot(sound);
audio.Play();
}
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast (endBarrel.position, transform.forward, hit, 100))
{
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
}
}
EDIT: Wait, line 39 IS exactly what you need. If it casts from the center of the screen then what is your endBarrel doing at the center of your screen? $$anonymous$$ake sure its a weapon and in the correct position.
Line 17 is the one that should be co$$anonymous$$g out of the center of your screen... And thats where you're currently applying your damage. So just move the damage message past line 39 ins$$anonymous$$d.
No that doesnt work i know this is asking quite alot but could you edit the script so it is right you dont have to if you dont want to im just wondering
No that still does not work would i need to tag my gun barrel or something
Answer by brandonsbarber · Jun 26, 2013 at 08:46 PM
Check out this answer here. I think this should help. To calculate direction, just subtract vectors from both ends of the gun.
That is assuming your gun is an actual object in the scene...
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Using RayCast to do Continuous Shooting? 1 Answer
RayCast Shooting not working 0 Answers
Make bullet launch at center of screen 2 Answers
Joystick Raycast Problem? 2 Answers