Search code examples
c#unity-game-engine3draycasting

Unity 3D Raycast not going in the right direction


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 character 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.


Solution

  • Start with the vectors you previously had:

    // Hand
    pos.x = transform.position.x;
    pos.y = transform.position.y -1.4f;
    pos.z = 0f;
    
    // Shoulder
    pos1.x = shoulder.transform.position.x;
    pos1.y = shoulder.transform.position.y;
    pos1.z = 15f;
    

    Substract the hand vector from the shoulder vector to get the distance (or delta) between the two points.

    Vector3 dir = pos1 - pos;
    
    // For bonus point you can set the length of the ray by using dir as a unit vector
    public float length;
    
    dir = dir.normalized * length;
    

    And finally feed the position of the shoulder and the new direction vector containing the direction and length of your ray to your function.

    Debug.DrawRay(pos1, dir, Color.yellow);