- Home /
Raycast off empty gameobject rather then camera.
I want to cast a ray(8 actually) from my airplanes gun(s). The problem is my script is designed to shoot the ray from the center of the camera. I need a way to project the ray forward from my gun(s).
#pragma strict
var Effect : Transform;
var TheDammage = 100;
function Update () {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));
if(Input.GetMouseButtonDown(0)){
if(Physics.Raycast (ray, hit, 100))
{
var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy (particleClone, 3);
hit.transform.SendMessage("ApplyDamage", TheDammage, SendMessageOptions.DontRequireReceiver);
}
}
}
Answer by MrSoad · Nov 15, 2014 at 11:11 PM
This line should help you, it casts from the object that it is on, in the objects forward direction, with "fRaycast_Distance" distance and "lmPlayer" layermask.
if (Physics.Raycast (transform.position, transform.forward, hit, fRaycast_Distance, lmPlayer)) {
Answer by Owen-Reynolds · Nov 12, 2014 at 03:51 AM
That code is using a specific shortcut to look from the camera to a specific point on the screen. But, in general, you can raycast "in the world" from any 3D point, in any 3D direction.
Looking at other examples of raycasts should let you see how it's done. For example, a player shooting a bullet is sometimes a raycast from the gun, in the direction it faces.
I was hoping for an example rather then a general answer.
Unity Answers is full of perfectly good examples of raycasts, esp. for shooting. Code snippets like you posted, with people explaining and making it work. Very popular subject.
Nothing I quickly type here is going to be as good as all that.
Your answer
![](https://koobas.hobune.stream/wayback/20220613171257im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Using CrossHair GUI to Determine Ray Spread 0 Answers
Raycast shooting 1 Answer
Gun script not working 3 Answers
Raycast shooting in the middle of the screen 1 Answer
How can I shooting script c#? 0 Answers