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. Dismiss Notice

Raycasting between objects. What am I doing wrong?

Discussion in 'Scripting' started by fullmetaljacket, Oct 6, 2014.

  1. fullmetaljacket

    fullmetaljacket

    Joined:
    Aug 19, 2014
    Posts:
    16
    Hi people. I have a problem that probably is solved easily, but several hours ago that I can not solve. I need to raycast from the camera to a Vector3 (not the cursor position, just a vector3 in the space).

    This point in space is just the direction that I want to direct the ray, but I need to know if in that direction, before or after this direction point, the ray collides with any object.

    This is the code I'm using, and does not work sp2 is the direction point

    RaycastHit pHit;

    if (Physics.Raycast (currentCamera.transform.position, sp2, out pHit, Mathf.Infinity)) {
    Debug.DrawLine (currentCamera.transform.position, sp2, Color.red);
    }
    else
    {
    Debug.DrawLine (currentCamera.transform.position, sp2, Color.white);
    }

    raycast.png
     
  2. fullmetaljacket

    fullmetaljacket

    Joined:
    Aug 19, 2014
    Posts:
    16
    I researched and found that linecast solves half the problem. I can find objects between the camera and sp2, but I can not find the ones that are beyond sp2.

    any ideas?
     
  3. djfunkey

    djfunkey

    Joined:
    Jul 16, 2012
    Posts:
    201
    I would raycast from the SP2, the opposite direction of the camera.
    Or you could check if the object hit is greater than the distance between the camera and SP2.
     
    fullmetaljacket likes this.
  4. fullmetaljacket

    fullmetaljacket

    Joined:
    Aug 19, 2014
    Posts:
    16
    This is a very good idea, Let me try...
     
    Last edited: Oct 7, 2014
  5. fullmetaljacket

    fullmetaljacket

    Joined:
    Aug 19, 2014
    Posts:
    16
    There is an easy way to "raycast the opposite direction of the camera"?
     
  6. fullmetaljacket

    fullmetaljacket

    Joined:
    Aug 19, 2014
    Posts:
    16
    This is the solution:

    To get a ray from point A in the direction of point B you can use point A as origin and (pointB - pointA).normalized as the direction
     
  7. djfunkey

    djfunkey

    Joined:
    Jul 16, 2012
    Posts:
    201
    Yeah that sounds about right :)