jeudi 29 juillet 2021

Cannot get If statements on RaycastHit2D to execute except for the top-most one

In my Unity 2D game, I have set up 3 different 2D Raycasts on the same GameObject for score-detection purposes with the help of boolean and if statements. The object in question today is a torus that is scrolling from right to left, which the player (the balloon) has to go through or avoid using up and down motion. The player gets more points when going through the torus as opposed to going around it.

The issue: Rayhit1 returns correctly when the player is detected inside the torus. But the code for Rayhit2 and Rayhit3 won't execute. Interestingly, if I put the code for Rayhit2 before Rayhit1, it would execute. Same is true for Rayhit3.

This is the "hit1" part for example:

if(!Rayhit1)
    {
         if(hit1.collider.name == "GameObject")
         {
              RayHit1 = true;
              score.value += 30;
         }
    }
if(!hit1)
    {
         RayHit1 = false;
    }

Snapshot of the game

Here are snippets of my code that concern the process of detecting score:

private bool RayHit1 = false;
private bool RayHit2 = false;
private bool RayHit3 = false;

void Update()
{
     int layer = 9;
     int layerMask = 1;
     RaycastHit2D hit1 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 72.0f), Vector2.up, 150.00f, layerMask);
     RaycastHit2D hit2 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y + 85.0f), Vector2.up, 600.00f, layerMask);
     RaycastHit2D hit3 = Physics2D.Raycast(new Vector2(transform.position.x + 5.0f, transform.position.y - 85.0f), Vector2.down, 600.00f, layerMask);

if(!Rayhit1)
{
     if(hit1.collider.name == "GameObject")
     {
          RayHit1 = true; //boolean to true for just 1 frame so that the score does not add more than once
          score.value += 30;
     }
}
if(!hit1)
{
     RayHit1 = false; //reset boolean to false when Raycast returns nothing
}

if(!Rayhit2)
{
     if(hit2.collider.name == "GameObject")
     {
          RayHit2 = true;
          score.value += 10;
     }
}
if(!hit2)
{
     RayHit2 = false;
}

if(!Rayhit3)
{
     if(hit3.collider.name == "GameObject")
     {
          RayHit3 = true;
          score.value += 10;
     }
}
if(!hit3)
{
     RayHit3 = false;
}
 
}

Aucun commentaire:

Enregistrer un commentaire