Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Problem with physics.raycast

Discussion in 'Scripting' started by ilyamep, Jul 7, 2015.

  1. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
    I want to know if "wall" is intersecting line between A and B objects
    This code is attached to object A and target object is B
    It works but in a strange way.

    If A and B objects position are like in first picture it works but, if I move object A like in second picture,
    raycast does not collide anymore. Same thing happens if I move object A to opposite side

    Thanks and sorry for my bad English





    Code (CSharp):
    1.     public GameObject target;
    2.     public RaycastHit hit;
    3.  
    4.     void Update () {
    5.             if(Physics.Raycast(transform.position, target.transform.position, out hit)){
    6.                 Debug.DrawLine(transform.position, target.transform.position);
    7.                 if(hit.collider.gameObject.tag == "wall"){
    8.                     print ("hit " + hit.transform.tag);
    9.                 }
    10.             }
    11.         }
     
  2. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    The second argument in Raycast is a direction, not a position. Try this :


    Code (CSharp):
    1. if(Physics.Raycast(transform.position, transform.position- target.transform.position, out hit))
    2. {
    3. //do stuff
    4. }
     
    ilyamep likes this.
  3. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
  4. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    DoomSamurai almost got it, try writing the second parameter like this :
    Code (CSharp):
    1. target.transform.position - transform.position
     
    ilyamep likes this.
  5. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
  6. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
    Thanks guys, I love you, you saved my time, your suggestion works very nice. :*
     
  7. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    my bad!
     
  8. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    Well it happens from time to time, I'll do the same mistakes from time to time :D.