I'm trying to implement a score counter in my Aframe scene, and so far I have this code but it isn't working. Would someone be able to take a look at the code below and spot the mistake I'm making? Many Thanks. D
AFRAME.registerComponent('score counter', {
schema: {
el: {
type: 'selector'
},
score:{
type: 'int',
default: 0
},
tick: function () {
var sceneEl = document.querySelector('a-scene');
var el1 = this.el;
var el2 = this.data.el;
var entity = document.querySelector('#score');
sceneEl.querySelector('a-box').addEventListener('click', function () {
this.data.score++;
this.data.score = 0;
entity.emit('updateScore');
AFRAME.utils.entity.setComponentProperty(entity, 'text.value', "score \n" + this.data.score);
}
});
The tick function happens really often, since it's usually used for drawing. So if you put your code there, your calling it every millisecond or so, and so you're just consuming more and more eventlisteners.
Here is the docs for it:
https://aframe.io/docs/0.7.0/introduction/writing-a-component.html#defining-a-behavior-with-the-tick-handler
That said, You'll want to put that code in the init function since it only occurs one time.
Also in your code your incrementing the score with ++
but right after your setting the score to zero.
Could you explain what you are trying to achieve with the click on the box?
Updated:
Here is a basic working example:
https://glitch.com/edit/#!/a-frame-scoreboard
Simply increment the score and set the new text value.
AFRAME.registerComponent('score-counter', {
schema: {
el: {
type: 'selector'
},
score:{
type: 'int',
default: 0
},
},
init: function () {
var sceneEl = document.querySelector('a-scene');
var scoreBoard = document.querySelector('#score');
sceneEl.querySelector('a-box').addEventListener('click', () => {
this.data.score++;
var newScore = 'Score: ' + this.data.score
scoreBoard.setAttribute('text', 'value', newScore)
})
}
});