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

Why aren't I picking up the first object every time, with a Raycast ?

Discussion in 'Scripting' started by Durge, Dec 11, 2016.

  1. Durge

    Durge

    Joined:
    Feb 23, 2015
    Posts:
    11
    I have never come across this before, and there are probably alternative ways to deal with this, but here goes -

    I have a SpaceShip, over a platform (A modified Cube Primitive). I am using the "Water" from the Standard Assets, so underneath that there is a plane to "hit", when the platform is not below. Thus I want to detect whether it is a Platform, or over the "seabed" (Tagged as "Base" in code") -

    void Update () {
    if (OverPlatform())
    isAbovePlatform = true;
    else
    isAbovePlatform = false;
    }

    bool OverPlatform()
    {
    RaycastHit hit;
    bool abovePlatform = false;
    if (Physics.Raycast(transform.position, -Vector3.up, out hit))
    {
    if (hit.transform.gameObject.tag.Equals("Platform"))
    {
    Debug.Log("Platform hit");
    abovePlatform = true;
    }
    else
    {
    Debug.Log("base hit");
    abovePlatform = false;
    }
    }
    return abovePlatform;
    }

    My problem is that when the ship is above the platform, on each iteration of Update(), it is alternating between the platform and the base, surely the platform, as the first object underneath, would be found first every time ?
     
  2. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    967
  3. Durge

    Durge

    Joined:
    Feb 23, 2015
    Posts:
    11
    My apologies, I was originally going to post this in "Answers", and did a straight C&P...

    Here's a screen shot from the Editor, and a little of the Console output. "Base" is of course out of view, below the water.
     

    Attached Files:

  4. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    967
    I don't see any reason why this would happen, maybe try to debug the raycast with Debug.DrawRay
     
    Durge likes this.
  5. Durge

    Durge

    Joined:
    Feb 23, 2015
    Posts:
    11
    Ah okay, thanks for that. A "facepalm" moment I'm afraid, I feel a little silly.... the reason why was that there were two rays - I had attached the same Detector script to a camera in the scene, for no real reason either, not that I recall... oh well....
     
    steego likes this.