-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathToolPickerBehavior.ts
More file actions
86 lines (71 loc) · 2.27 KB
/
ToolPickerBehavior.ts
File metadata and controls
86 lines (71 loc) · 2.27 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@component
export class ToolPickerBehavior extends BaseScriptComponent {
@input
public toolPrefabs: ObjectPrefab[]
@input
public toolSpawnPoints: SceneObject[]
public toolSpawnPointsT: Transform[]
private latestObj: SceneObject[]
private latestObjT: Transform[]
private yOffset = 5
private distanceOffset = 15
@input
public containerObj: SceneObject
onAwake() {
this.init()
this.createEvent("UpdateEvent").bind(this.onUpdate.bind(this))
}
init() {
this.toolSpawnPointsT = []
this.latestObj = []
this.latestObjT = []
this.spanwAllTools()
}
spanwAllTools() {
this.toolSpawnPoints.forEach((value, ind) => {
const spawnPoint = value
this.toolSpawnPointsT[ind] = spawnPoint.getTransform()
this.spawnAndReplace(ind)
})
}
onUpdate() {
this.toolSpawnPoints.forEach((value, ind) => {
try {
const spawnPointT = this.toolSpawnPointsT[ind]
const objectT = this.latestObjT[ind]
// Check if object still exists (might have been destroyed by GrabbableObject)
if (!objectT) {
this.spawnAndReplace(ind)
return
}
// Try to get scene object - if it fails, object was destroyed
const sceneObj = objectT.getSceneObject()
if (!sceneObj) {
this.spawnAndReplace(ind)
return
}
// Check distance
const objPos = objectT.getWorldPosition()
const spawnPos = spawnPointT.getWorldPosition()
if (objPos.distance(spawnPos) > this.distanceOffset) {
sceneObj.setParent(null)
this.spawnAndReplace(ind)
}
} catch (e) {
// Object was destroyed mid-update, spawn a new one
print(`ToolPickerBehavior: Object at index ${ind} was destroyed, respawning`)
this.spawnAndReplace(ind)
}
})
}
spawnAndReplace(ind) {
const spawnPos = this.toolSpawnPointsT[ind].getWorldPosition()
spawnPos.y += this.yOffset
const nObject = this.toolPrefabs[ind].instantiate(this.containerObj)
nObject.enabled = true
nObject.getTransform().setWorldPosition(spawnPos)
nObject.getTransform().setWorldRotation(this.toolSpawnPointsT[ind].getWorldRotation())
this.latestObj[ind] = nObject
this.latestObjT[ind] = nObject.getTransform()
}
}