- Home /
The question is answered, right answer was accepted
If statement not working
I am trying to make it so a game object flips if the player is not in it's raycast but it does not seem to work. I know that the raycast works fine because I tested it by logging the name of the object the raycast hit, but my if statement with a boolean does not seem to work. Please help. Thanks!
public Transform viewPoint;
public Transform target;
public float speed = 3f;
public float viewDistance = 10f;
bool FacingPlayer;
void Update()
{
RaycastHit2D hitTarget = Physics2D.Raycast(viewPoint.position, viewPoint.right);
if (Vector3.Distance(transform.position, target.position) < viewDistance)
{
if (hitTarget)
{
FacingPlayer = true;
}
if (!FacingPlayer)
{
Flip();
}
}
}
void Flip()
{
transform.Rotate(0f, 180f, 0f);
}
in other words, the Flip() function doesn't get called when it is supposed to :\
Is outer if statement evaluating true (i.e., are you sure that the distance to target is less than viewDistance)? Or is it just the inner if statements that aren't evaluating the way you want?
Answer by RogueMacro · Jan 20, 2019 at 04:55 PM
@goldenbergdaniel8 I believe that the second boolean statement will (almost) never run. This is because you are first checking for if the raycast was a success, not if it hit the player. I suggest you do something like this:
if (hitTarget.collider.tag != "Player")
{
Flip();
}
Answer by Bunny83 · Jan 20, 2019 at 05:21 PM
This statement:
if (hitTarget)
is pointless since hitTarget is a struct. This statement will always be true. You may pay more attention to the example given in the documentation. You have to check if hitTarget.collider is null or not. If it's null, nothing was hit. If it's not null it contains a reference to the collider that was hit.
So it should be
if (hitTarget.collider != null)
{
FacingPlayer = true;
}
Note that you never set FacingPlayer back to false. So once this if condition is true, FacingPlayer will be set to true and stay true until you explicitly set it back to false. In the code you've posted you never set it back to false.
RaycastHit2D has an operator for conversion to bool. There is no need to check if we hit a collider.
public static implicit operator bool (RaycastHit2D hit);