0
votes

I've been trying to cycle through colors using a custom component.

<script>
  AFRAME.registerComponent('floor-cycle', {
    init: function () {
      var sceneEl = document.querySelector('a-scene');
      var floorEl = sceneEl.querySelector('#floor')
        status = 1;
        floorEl.addEventListener('click', function () {
        if(status==1) {
        floorEl.setAttribute('color', 'red'); status = 2
        }
        else if(status==2) {
        floorEl.setAttribute('color', 'blue'); status = 3;
        }
        else if(status==3) {
        floorEl.setAttribute('color', 'green'); status = 1
        }
      }                    
      );
    }
  }); 
</script>

The component uses status to set the color attribute on click event, however this seems inefficient. Can this be implemented using an array rather than status?

demo - https://codepen.io/MannyMeadows/pen/GWzJRB

1

1 Answers

1
votes

You can make an array ['red','green','blue'] and Cycle through it:

colors = ['red','green','blue'];
let i = 0;
floorEl.addEventListener('click',function(){
    floorEl.setAttribute('material','color', colors[i]);
    function add(){(i==colors.length-1) ? i = 0 : i++;}
    add();
});

Seems better as the array is now dynamic, not sure how about the performance. working fiddle here: https://jsfiddle.net/gftruj/g9wfLgab/2/