- Home /
Raycast isn't going straight
void FixedUpdate () {
RaycastHit hit;
Ray ray = new Ray (Barrel.transform.position, transform.forward);
if (Input.GetMouseButtonDown (0)) {
if(Physics.Raycast (ray,out hit,100)) {
GameObject particleClone;
particleClone = Instantiate (par, hit.point, Quaternion.LookRotation (hit.normal)) as GameObject;
Destroy (particleClone,2);
hit.transform.SendMessage ("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
}
Vector3 forward = transform.TransformDirection (Vector3.forward) * 100;
Debug.DrawRay (Barrel.transform.position, forward, Color.red);
}
When I press the mouse button the object I'm instantiating doesn't always appear. Also, my Debug shows two rays one going straight and the other going up. I'm fairly new to using raycasts, so I'm not sure whats wrong.
It is a bit strange that you are getting the position of your Raycast()/DrawRay() from 'Barrel.transform.position, but you are getting the direction from the game object this script is attached to (transform.position). Usually the code uses both position and direction form the same game object.
Answer by AndyMartin458 · Jul 23, 2014 at 09:26 PM
Don't get input in FixedUpdate() or else you will miss some mouse clicks (as you've noticed). Instead, only take input in Update().
--EDIT apparently it does take into account the length of the forward vector. I've edited the answer/
void Update ()
{
if (Input.GetMouseButtonDown (0))
{
//Only do these raycasts when necessary
RaycastHit hit;
Ray ray = new Ray (Barrel.transform.position, transform.forward);
if(Physics.Raycast (ray,out hit,100))
{
GameObject particleClone;
particleClone = Instantiate (par, hit.point, Quaternion.LookRotation (hit.normal)) as GameObject;
Destroy (particleClone,2);
hit.transform.SendMessage ("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
}
Vector3 forward = Barrel.transform.TransformDirection(Vector3.forward) * 10;
//Try this, it certainly should not draw two different rays
Debug.DrawRay (Barrel.transform.position, forward, Color.red);
}
Your answer