I'm trying to display some text when the camera move closer to the sphere. The idea is when user see the sphere moves much closer, the text then shows up, let's say, "Hello". But right now I only know how to add text with fixed position by using a-entity, I have no idea how to detect the distance between camera and sphere, and display text when user can see the sphere comes closer. Here's my code now:
<html>
<head>
<script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script>
</head>
<body>
<a-scene>
<a-sphere position="0 0 0" perspective="true" radius="1.5" color="#aaa" id="sphere1"></a-sphere>
<a-entity position="4.5 2 0" text="width: 10; color: white; value: Hello"></a-entity>
<a-sky color="#000"></a-sky>
<a-entity class="camwrap" position="0 0 0">
<a-camera look-controls wasd-controls="fly:true acceleration:1" near="1" position="0 0 20" user-height="0" fov="60">
</a-camera>
</a-entity>
</a-scene>
<script>
const cam = document.querySelector("a-camera");
setTimeout(function() {
cam.components["wasd-controls"].keys["KeyW"] = true;
}, 1000);
</script>
</body>
Any thoughts?
If You know the camera position, and the sphere position - you can calculate the distance:
1) sqrt((x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2)
,
2) or by using the THREE.js a.distanceTo(b)
method.
Throw your calculations into a custom component, and check the distance in a tick
function:
init: function() {
this.cam = document.querySelector("[camera]")
this.sphere = document.querySelector("a-sphere")
},
tick: function() {
let camPos = this.cam.object3D.position
let spherePos = this.sphere.object3D.position
let distance = camPos.distanceTo(spherePos)
if (distance < 5) {
// camera closer than 5m, do something
}
}
Check it out in this fiddle.