Reputation: 357
I'm using A-Frame and want an object to move along with the camera. To do this, I put together a component that updates the object's position based on the camera position:
AFRAME.registerComponent('follow', {
schema: {
distance: {type: 'vec3'},
target: {type: 'selector'}
},
tick: function() {
const targetItem = this.data.target;
const relativePosition = this.data.distance
var tempPos = targetItem.getAttribute("position").split(" ").map(Number);
targetPos = new THREE.Vector3(relativePosition.x + tempPos[0], relativePosition.y + tempPos[1], relativePosition.z + tempPos[2]);
this.el.setAttribute('position', targetPos)
}
});
This works fine when I use init
instead of tick
but since it's an init function it only updates it once at the start of the scene. For some reason, when I use tick
everything breaks. Am I using it wrong? Should I do something different to continually update it's position?
Thanks in advance!
Edit: I should mention the goal is to have something follow around, but not be fixed to your view. Think Navi from Ocarina of Time.
Upvotes: 1
Views: 2110
Reputation: 357
Received a solution from outside SO:
I needed to put my WASD controller on the entity containing the camera:
<a-entity id="character" position="0 2 3" wasd-controls look-controls>
<a-entity id="camera" camera>
<a-ring radius-outer="0.03" radius-inner="0.02"
position="0 0 -1"
material="color: cyan; shader: flat"
cursor="fuse: true; fuseTimeout: 500">
</a-ring>
</a-camera>
</a-entity>
Then, I needed to change the function:
tick() {
const targetItem = this.data.target;
var distance = this.data.distance;
var targetPosition = targetItem.getAttribute('position');
this.el.setAttribute('position',{
x: targetPosition.x + distance.x,
y: targetPosition.y + distance.y,
z: targetPosition.z + distance.z
});
And then it worked!
Upvotes: 3