Reputation: 387
I have a cube in Unity3D. I know the vectors of its 8 vertices. It is rotated and scaled in 3D around all axes. How can I instantiate an object at run time inside that cube at a random position?
Upvotes: 1
Views: 5097
Reputation: 6132
If you know the 8 vertices of your cube, it's easy to randomize an object inside of this cube. Consider the random object to have an x
, y
and z
value in the position of the Transform. Both UnityScript and C# provide a nice Random
class which can easily give you a random number between two values. Use this class three times:
x
value and the min x
value of all 8 vertices.y
value and the min y
value of all 8 vertices.z
value and the min z
value of all 8 vertices.Next, create your gameobject which has to be instantiated in this cube, and use the x
, y
and z
value you've calculated from above three steps. That would randomly create your object in the cube.
Note that if your random object has a certain size, it would technically be possible to generate the object randomly on the edge of the cube, thus letting the random object 'stick out' of the cube. To avoid that, make sure to substract half the size of the object from the max values you enter in the randomize function and to add up half the size of the object from the min values you enter in the randomize function.
EDIT: To get your points when the object is rotated, you can use cube.transform.localScale / 2
. This will get you the local position of one of the cube's corners. Vector3.Scale(cube.transform.localScale / 2, new Vector3(1,1,-1))
will get you one of the others (different combinations of 1 and -1 there will get you all eight). Then, to find them in world space, use cube.transform.TransformPoint()
.
Upvotes: 2
Reputation: 4174
If I understand what you're trying to do correctly, I'd probably suggest something like the following.
public class Instantiation : MonoBehaviour {
void Start() {
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.AddComponent<Rigidbody>();
cube.transform.position = new Vector3(x, y, 0);
}
}
}
}
It will create the GameObject cube (or whatever you desire) at the new transform.position. However instead of it's position being a specific Vector3, you have it as a randomly generated Vector3 from a new method. This method will be created to randomise the numbers for x then y and z within specific boundaries. You then just feed it into the new position.
I hope that makes sense, I'm not a fantastic teacher.
Edit: http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html this is a good reference for instantiating Prefabs. Your run time instantiated object should be of a prefab.
Upvotes: 1