forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpawnRandomPhysicsBodies.cs
More file actions
56 lines (49 loc) · 2.08 KB
/
Copy pathSpawnRandomPhysicsBodies.cs
File metadata and controls
56 lines (49 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using Unity.Physics;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Collections;
using UnityEngine;
using Unity.Transforms;
using Collider = Unity.Physics.Collider;
[Serializable]
public class SpawnRandomPhysicsBodies : MonoBehaviour
{
public GameObject prefab;
public float3 range;
public int count;
void OnEnable()
{
if (this.isActiveAndEnabled)
{
// Create entity prefab from the game object hierarchy once
Entity sourceEntity = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, World.Active);
var entityManager = World.Active.EntityManager;
var positions = new NativeArray<float3>(count, Allocator.Temp);
var rotations = new NativeArray<quaternion>(count, Allocator.Temp);
RandomPointsOnCircle(transform.position, range, ref positions, ref rotations);
BlobAssetReference<Collider> sourceCollider = entityManager.GetComponentData<PhysicsCollider>(sourceEntity).Value;
for (int i = 0; i < count; i++)
{
var instance = entityManager.Instantiate(sourceEntity);
entityManager.SetComponentData(instance, new Translation { Value = positions[i] });
entityManager.SetComponentData(instance, new Rotation { Value = rotations[i] });
entityManager.SetComponentData(instance, new PhysicsCollider { Value = sourceCollider });
}
positions.Dispose();
rotations.Dispose();
}
}
public static void RandomPointsOnCircle(float3 center, float3 range, ref NativeArray<float3> positions, ref NativeArray<quaternion> rotations)
{
var count = positions.Length;
// initialize the seed of the random number generator
Unity.Mathematics.Random random = new Unity.Mathematics.Random();
random.InitState(10);
for (int i = 0; i < count; i++)
{
positions[i] = center + random.NextFloat3(-range, range);
rotations[i] = random.NextQuaternionRotation();
}
}
}