- Home /
Keeping raycast position and rotation equal as gameObject
Hello,
I'm currently making a climbing system from scratch and am having some problems with the raycasts. I have two raycasts shooting diagonally from a bit up and to the front of my character. My problem is that when I rotate my character the raycast origin point 'z' coordinate stays the same.
I have tried the transform.TransformDirection method and it actually gets worse. The only solution I could think of right now was to create an empty gameObject and child it to the character and getting its position through the inspector, but there's got to be a way...
The raycasts are the blue lines in the images, I also have a link to a gif so you can understand clearly what the problem is.
Debug.DrawRay(transform.position + Vector3.up * 1f + Vector3.forward * .3f, transform.TransformDirection(new Vector3(1f, -1.5f, 0)) * 1.5f, Color.blue);
Debug.DrawRay(transform.position + Vector3.up * 1f + Vector3.forward * .3f, transform.TransformDirection(new Vector3(-1f, -1.5f, 0)) * 1.5f, Color.blue);
Answer by jstopyraIGG · Feb 20, 2019 at 12:25 AM
Use transform.forward instead of Vector3.forward. Vector3.forward is 1 unit forward in world space (always {0, 0, 1}), transform.forward is 1 unity forward in local space, which depends on your objects rotation. The TransformDirection stuff is in world space as well, and you should do local space.
//get a vector half way between left and forward.
Vector3 leftDir = Vector3.Lerp(transform.forward, -transform.right, 0.5f);
//-1.5f how much far down.
leftDir.y = -1.5f;
Vector3 rightDir = Vector3.Lerp(transform.forward, transform.right, 0.5f);
rightDir.y = -1.5f;
Debug.DrawRay(transform.position + Vector3.up * 1f + transform.forward * .3f, leftDir.normalized *
1.5f, Color.blue);
Debug.DrawRay(transform.position + Vector3.up * 1f + transform.forward * .3f, rightDir.normalized *
1.5f, Color.blue);
Try this, I have not tested this, but this should create ray going from above your head, diagonally down in front of you.