Search Unity

Why does this work?

Discussion in 'Getting Started' started by drdenner, Nov 11, 2015.

  1. drdenner

    drdenner

    Joined:
    Jun 24, 2014
    Posts:
    32
    (Im a beginner, so if im doing something wrong/stupid, please let me know)

    I made a function that detects if a there is Line of Sight between two Transforms.

    public void Detecting (Transform start, Transform end, float range)
    {
    Vector3 direction = start.position - end.position;
    float angle = Vector3.Angle (direction, start.forward);

    if (angle < fieldOfViewAngle * 0.5f) {
    RaycastHit hit;

    if (Physics.Raycast (start.position + start.up, -direction.normalized, out hit, range)) {
    Debug.Log (hit.collider.tag);
    if (hit.collider.gameObject.tag == "Player") {
    inSight = true;
    } else {
    inSight = false;
    }
    }
    }
    }

    The function works, but i dont under stand this line:
    if (Physics.Raycast (start.position + start.up, -direction.normalized, out hit, range)) {

    Why the '-' in '-direction' ?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    First, please use CODE tags around your code to make it readable... easiest way to do that is with the "Insert" button, right between the movie filmstrip and the floppy disk in the formatting bar.

    Anyway, the reason you're negating direction here is because of the way direction was computed in the beginning: start minus end. That gives you a vector that points in the direction of start, from the end.

    To see this, suppose you're on a simple number line, like say start is (5,0,0) and end is (20,0,0). So we can ignore Y and Z and just consider X. start (5) minus end (20) gives you -15, that is, it points in the negative direction.

    But your ray is otherwise defined starting at start. So this direction is backwards; you want a vector that points towards the end. The "proper" fix for this would be to change how direction is defined in the first place; make it end - start, rather than start - end. But you can also just negate it (use -direction or -direction.normalized), and that does the same thing.
     
  3. drdenner

    drdenner

    Joined:
    Jun 24, 2014
    Posts:
    32
    Thanks for the answer.
     
  4. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Using code tags properly:
    http://forum.unity3d.com/threads/using-code-tags-properly.143875/