Implementing a score counter in A-Frame

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 05:15:09

问题


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);   
}

});


回答1:


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)
    })
  }
});


来源:https://stackoverflow.com/questions/48216250/implementing-a-score-counter-in-a-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!