- Home /
Question by
kable2580 · Aug 17, 2017 at 08:44 AM ·
raycastif-statementsvector2raycasthit2d
Using Vector2.negativeInfinity in if else
I have written a function to use raycast2d to detect enemies and return their positions. Here is the code:
public Vector2 detect() //detect an enemy, return it's position. If enemy not found, return Vector2.negativeInfinity
{
//Debug.Log(range);
RaycastHit2D [] detectionInfoRight = Physics2D.RaycastAll(gameObject.transform.position, Vector2.right, range);
RaycastHit2D [] detectionInfoLeft = Physics2D.RaycastAll(gameObject.transform.position, Vector2.left, range);
foreach(RaycastHit2D info in detectionInfoLeft)
{
if(info.collider.gameObject.tag == "Enemy")
{
Debug.Log("Enemy found, returning position: " + info.collider.gameObject.transform.position);
return info.collider.gameObject.transform.position;
}
}
foreach(RaycastHit2D info in detectionInfoRight)
{
if (info.collider.gameObject.tag == "Enemy")
{
Debug.Log("Enemy found, returning position: " + info.collider.gameObject.transform.position);
return info.collider.gameObject.transform.position;
}
}
Debug.Log("No enemies");
return Vector2.negativeInfinity;
}
In my update function I used a if-else statement to check whether or not to attack:
void Update () {
if (detect() != Vector2.negativeInfinity)
{
rb2d.velocity = Vector2.zero; //stop, and be ready to engage
Debug.Log("Enemy Detected, position: " + detect());
}
else
{
rb2d.velocity = new Vector2(patrolBoat.speed, 0);
}
}
The problem is, when no enemy is sighted detect() returns Vector2.negativeInfinity correctly, but it still enters the if statement and prints "Enemy Detected, position: (-Infinity, -Infinity)".
Comment