Skip to content

Instantly share code, notes, and snippets.

@Ashwinning
Last active April 19, 2023 18:45
Show Gist options
  • Save Ashwinning/269f79bef5b1d6ee1f83 to your computer and use it in GitHub Desktop.
Save Ashwinning/269f79bef5b1d6ee1f83 to your computer and use it in GitHub Desktop.
Find a random point between two Vector3 points. #gistblog #unity3d #c#
/// <summary>
/// Returns a random vector3 between min and max. (Inclusive)
/// </summary>
/// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
/// https://gist.github.com/Ashwinning/269f79bef5b1d6ee1f83
public Vector3 GetRandomVector3Between (Vector3 min, Vector3 max)
{
return min + Random.Range (0, 1) * (max - min);
}
/// <summary>
/// Gets the random vector3 between the min and max points provided.
/// Also uses minPadding and maxPadding (in metres).
/// maxPadding is the padding amount to be added on the other Vector3's side.
/// Setting minPadding and maxPadding to 0 will make it return inclusive values.
/// </summary>
/// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
/// <param name="minPadding">Minimum padding.</param>
/// <param name="maxPadding">Max padding.</param>
/// https://gist.github.com/Ashwinning/269f79bef5b1d6ee1f83
public static Vector3 GetRandomVector3Between(Vector3 min, Vector3 max, float minPadding, float maxPadding)
{
//minpadding as a value between 0 and 1
float distance = Vector3.Distance(min, max);
Vector3 point1 = min + minPadding * (max - min);
Vector3 point2 = max + maxPadding * (min - max);
return GetRandomVector3Between(point1, point2);
}
@Kyonru
Copy link

Kyonru commented Jun 18, 2020

I would suggest changing Random.Range (0, 1) to Random.Range (0f, 1f).

@brucemax
Copy link

I would suggest changing Random.Range (0, 1) to Random.Range (0f, 1f).

Useful advice! Thanks!

@bombarie
Copy link

bombarie commented Nov 27, 2022

I would suggest changing Random.Range (0, 1) to Random.Range (0f, 1f).

Came here to say this too. It MUST be Random.Range(0f, 1f) since using ints in Random.Range excludes the last item. So in fact here it would always equate to return min + 0 * (max - min); which just returns min.

@developerJuiceLozzoc
Copy link

I came here investigating vectors in my swiftui SceneKit app. of course the majority of the content I need is implemented on some GIST by a unity C# dev. oh well. thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment