antfarmar / Unity-3D-Asteroids

A simple Asteroids clone. In 3D.
The Unlicense
65 stars 15 forks source link

Asteroid Spawning: Randomized Algorithm Choice #11

Closed antfarmar closed 8 years ago

antfarmar commented 8 years ago

Currently algorithm:

antfarmar commented 8 years ago

Implemented as a fully random world spawn position, checking potential spawn points against a sphere collider child on the ship, using the static Physics.CheckSphere function. Allows the ship to be active and moving between levels.

The code:

public void SpawnRandomPosition()
    {
        int mask = LayerMask.GetMask("ShipSpawnSphere");
        Vector3 spawnPosition;
        bool hit = false;

        do
        {
            Vector3 randomPosition = new Vector3(Random.value, Random.value, 0f);
            spawnPosition = Camera.main.ViewportToWorldPoint(randomPosition);
            hit = Physics.CheckSphere(spawnPosition, 5f, mask);
        } while(hit);

        spawnPosition.z = 0f;
        transform.position = spawnPosition;
    }