- Home /
Trouble with raycasting
I would like to fire a raycast from the tip of my gun forward 10 units, but for some reason the end of my raycast is fixed on a particular location rather than pointing forward and I'm not sure why, the image below should show my issue, the if statement always displays "hitting", here is the code I am using:
void Update
{
Vector3 fwd = gunPos.transform.TransformDirection(Vector3.forward);
Debug.DrawLine(gunPos.transform.position, fwd, Color.green);
if (Physics.Raycast(gunPos.transform.position, fwd, 10))
{
Debug.Log("hitting");
}
else
Debug.Log("Not Hitting");
}
EDIT
This is is what I'm using now, the end of the ray is no longer fixed but the ray does not rotate with the player and continuously fires forward, I've added another photo to better illustrate, the ray works now but when I move my character the Z position of my gunPos stays in the same spot when i need it to rotate with the player.
void Update()
{
RaycastHit hit;
Ray myRay = new Ray(gunPos.transform.position, Vector3.forward);
Debug.DrawRay(gunPos.transform.position, Vector3.forward * 10);
if (Physics.Raycast(myRay, out hit, 10))
{
Debug.Log("hitting");
}
else
Debug.Log("NOT hitting");
}
Answer by ivanbozovic · Jul 20, 2015 at 05:44 PM
Hi, this line is the problem:
Vector3 fwd = gunPos.transform.TransformDirection(Vector3.forward);
Try using gunPos.transform.forward instead of Vector3.forward
attach an empty child GameObject at the end of the gun, make sure Z Axis is forward
Thats how I have it set up currently, but the z axis seems to be in world space when I need it to be in local