Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Why my RayCast doesn't work as expected

Discussion in 'Physics' started by unity_408540137, Jan 18, 2023.

  1. unity_408540137

    unity_408540137

    Joined:
    Oct 23, 2022
    Posts:
    44
    My RayCast practicce scripts will be below

    RaycastHit hitinfo;
    transform.Translate(transform.TransformDirection(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")));
    Debug.DrawRay(shoot.transform.position,shoot.transform.TransformDirection(-Vector3.right)*10,Color.red);
    bool collide = Physics.Raycast(shoot.transform.position,shoot.transform.TransformDirection(-Vector3.right)*10,out hitinfo,20f);
    if(collide)
    {
    Debug.Log("hit something");
    }

    else
    {
    Debug.Log("hit nothing");

    }
    }

    In play mode, as first beginning, the ray coming from the shoot hit a Cube, and console Debug.Log-->Hit Something

    But when I move the shooter the place, and move back , targeting the Cube, console no longer Debug.Log
    -->Hit Something. It always say "Hit Nothing"
    That's very weird, at first it does work, but when move back it doesn't work anymore
     

    Attached Files:

  2. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    2,063
    What's "shoot" in your script?

    You've moving the transform of the object the component is added to using the input axis, but then you're raycasting from "shoot" which seems to be a different object.

    As a side note, shoot.transform.TransformDirection(-Vector3.right) is the same as -shoot.transform.right
     
  3. unity_408540137

    unity_408540137

    Joined:
    Oct 23, 2022
    Posts:
    44
    Yes, the shoot means the rectangle attached to the capsule
    I want to draw ray from shoot position; therefore I use shoot.transform.position.

    That's very weird, at first it works, and returns gameobject such as cube1, cube2,..
    but when moving back, then it doesn't work as it did before.
     
  4. lightbug14

    lightbug14

    Joined:
    Feb 3, 2018
    Posts:
    447
    Raycast asks for a direction (normalized), there is no need for that "*10".