How to add user interactions?

Changing color with click event

To change the color of our object with interactions, first we will add a material.
1
var boxMaterial = new BABYLON.StandardMaterial("material", scene);
2
boxMaterial.diffuseColor = BABYLON.Color3.Random();
3
box.material = boxMaterial;
Copied!
Now we can add a click event and change the color and position with the click
1
box.actionManager = new BABYLON.ActionManager(scene);
2
box.actionManager.registerAction(new BABYLON.ExecuteCodeAction(
3
BABYLON.ActionManager.OnPickTrigger,
4
function (evt) {
5
var sourceBox = evt.meshUnderPointer;
6
7
//move the box upright
8
sourceBox.position.x += 0.1;
9
sourceBox.position.y += 0.1;
10
​
11
//update the color
12
boxMaterial.diffuseColor = BABYLON.Color3.Random();
13
}));
Copied!
Babylon.js Playground
Playground click event demo

Dragging an object

1
//Create pointerDragBehavior in the desired mode
2
//var pointerDragBehavior = new BABYLON.PointerDragBehavior({});
3
//var pointerDragBehavior = new BABYLON.PointerDragBehavior({dragPlaneNormal: new BABYLON.Vector3(0,1,0)});
4
var pointerDragBehavior = new BABYLON.PointerDragBehavior({dragAxis: new BABYLON.Vector3(1,0,0)});
5
6
// Use drag plane in world space
7
pointerDragBehavior.useObjectOrientationForDragging = false;
8
​
9
// Listen to drag events
10
pointerDragBehavior.onDragStartObservable.add((event)=>{
11
console.log("dragStart");
12
console.log(event);
13
})
14
pointerDragBehavior.onDragObservable.add((event)=>{
15
console.log("drag");
16
console.log(event);
17
})
18
pointerDragBehavior.onDragEndObservable.add((event)=>{
19
console.log("dragEnd");
20
console.log(event);
21
})
22
​
23
// If handling drag events manually is desired, set move attached to false
24
// pointerDragBehavior.moveAttached = false;
25
​
26
sphere.addBehavior(pointerDragBehavior);
Copied!
Babylon.js Playground
Dragging an object in 6 Degrees of Freedom.
Babylon.js Playground
Solution
Babylon.js Playground
​
​