I want the raycast to be pointing forward along the x axis of a cube in my scene. Instead the raycast starts at the origin of the cube and then points towards the origin of the scene (0,0,0). The length of the raycast is as long as it needs to be in order to reach the origin, despite me giving it a specific length.
void Update () {
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawLine (transform.position, transform.forward, Color.red);
if (Physics.Raycast (transform.position, fwd, out hit, 10)) {
print ("There is something in front of the object!");
}
}
Your problem is that you use Debug.DrawLine which expects two worldspace points. However you pass one worldspace point and a direction vector. Direction vectors are normalized (have a length of 1f). So since you treat the direction vector as position it’s always around the origin (in the range ±1 on each axis).
I think i know what’s wrong, but ima beginner too =P. I dont really understand what you wanted to do. If you wanted to check raycast in the x axis from the object or front of the object. but its almsot the same. just use transfrom.direction for the forward or trunk it more to get its x value to check the x axis =).
Sorry for poor english… not my native.
why you want to transform the direction? i bet the problem is there.
I use raycast in collision avoidance ai system with the same generation. you should jsut simply use the ray construktor as Ray ray = new Ray (gameObject.transform.position, gameObject.transform.forward);
and it will make you a ray that will be started at the center of your gameObject and points towards the object forward vector. After that you can check wha it hits easily.
transform.TransformDirection doesn’t return the transform’s world coordinates, just a Vector3 that equates to what direction you want in relation to the object, at least that’s what I think because I’ve had a similar problem to yours before.