Friday, 27 March 2015

Unity 5: Vector3.Distance

1 Hour Research.

    I am trying to make it so enemies will spawn at MIN distance of 100 unites away from the player in any direction. I tried numerous while loops with many playerObject.transform.position + or - 100 bools in it to no avail. Then I found Vector3.Distance. The code I could use for this is:

float distance = Vector3.Distance(enemyShip.transform.position, playerObject.transform.position)

    It calculates the total distance from the enemy ship to the player ship. But then I realized that there are nearly an infinite number of floats... So if I were to use:

                        while (distance < 100f)
                        {
                            enemyShip.transform.position = new Vector3(playerObject.transform.position.x + Random.Range(-125, 125), 0, playerObject.transform.position.z + Random.Range(-125, 125));
                        }


    It would go through several million calculations before it found a distance that may be equal to greater than 100.

    Back to the drawing board.

Edit****************************
1 Hour Code/Assets

I found a use for Vector3.Distance, when creating a new level this code will take a number of random game objects and spawn them, the if statement makes it so they will not spawn within 100 unity units of the player GameObject. In this case for random objects they all need to have the same names with different numbers, you cannot miss numbers else the code will break.

for (int c = 0; c < NumberOfPlanets; c++)
{
    int randomPlanet = Random.Range(1,5);
    Object planetClone = Resources.Load("Planet"+randomPlanet) as GameObject;
    GameObject planet = (GameObject)Instantiate(planetClone);
    planet.transform.position = new Vector3(Random.Range(-500, 500),0,Random.Range(-500, 500));
    if ((float)Vector3.Distance(planet.transform.position,player.transform.position) < 100f )
    {
        planet.transform.position = new Vector3(Random.Range(-500, 500),0,Random.Range(-500, 500));
    }
}

No comments:

Post a Comment