GetRandomInDonut() – Random location in a donut area

[tweetmeme source=”neoRiley” only_single=false]The scenario is: you’ve got a player object, and you want to spawn enemy characters away from the player, but within a range.  Basically, within a donut area, right?

using UnityEngine;
using System.Collections;

public class Utils
{
    public static Vector3 GetRandomInDonut(float min, float max)
    {
        float rot = Random.Range(1f, 360f);
        Vector3 direction = Quaternion.AngleAxis(rot, Vector3.up) * Vector3.forward;
        Ray ray = new Ray(Vector3.zero, direction);

        return ray.GetPoint( Random.Range(min, max) );
    }
}

To use it, just call it with the minimum and maximum distance away you want your new position to be. Then add it to the transform of where your player’s spawn point is:

public void LoadCharacters()
{
    // add the transform's position since the returned position is from a location of Vector3.zero
    Vector3 pos = transform.position + GetRandomInDonut(20f, 50f);
}

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s