- Home /
Raycast does not go in the right direction
Hello, i wrote some code that is supposed to emit a raycast from the gameobject shoulder and goes through the gameobject hand. this is to give the direction that the mouse is so if my charecter picks up an item they could used that item in that direction, ie gun shoots in that direction. currently i only have it drawing the cast to debug it because the cast emits from the correct position but does not go through the hand. ive tried multiple iterations of this code based on the answers of previous question but it doesn't seem to work. the game is a 2.5D side scroller.
pos.x = transform.position.x;
pos.y = transform.position.y -1.4f;
pos1.x = shoulder.transform.position.x;
pos1.y = shoulder.transform.position.y;
pos1.z = 15f;
pos.z =0f;
RaycastHit info;
Debug.DrawRay(pos1, pos, Color.yellow);
the code is on the hand gameobject, it also does strange things when i move the charter from the orgin , like flip directions and only rotates halfway and doesn't emit the raycast in the opposite direction.
Answer by AnArt · Mar 08, 2019 at 08:21 AM
Hey orion! If you want to get the position of your hand, go ahead and use Vector3! Something like this should work:
public class NewBehaviourScript : MonoBehaviour
{
public Transform hand;
public float distance = 5;
Vector3 pos;
void Update()
{
pos = new Vector3(hand.position.x, hand.position.y - 1.4f, hand.position.z);
}
void OnDrawGizmos()
{
Debug.DrawRay(pos, pos + transform.forward * distance, Color.yellow);
}
}
I hope this worked for you! If your line doesn't show up, make sure to toggle on Gizmos in the player window next to "Maximize on Play". And if it doesn't point in the right direction, go ahead and change the transform.forward to transform.up or transform.down! OR if you want it to point forward and not change it's angle with the hand, go ahead and use Vector3.forward instead!
public class NewBehaviourScript : MonoBehaviour
{
public Transform hand;
public float distance = 5;
Vector3 pos;
void Update()
{
pos = new Vector3(hand.position.x, hand.position.y - 1.4f, hand.position.z);
}
void OnDrawGizmos()
{
Debug.DrawRay(pos, pos + Vector3.forward * distance, Color.yellow);
}
}
i think you are confusing raycast with debug.drawline. raycast works with directions while drawline with positions.
Debug.DrawLine(pos, pos + transform.forward * distance, Color.yellow);