Aframe: cycle through colors using array

不羁岁月 提交于 2019-12-12 06:26:28

问题


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:


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/



来源:https://stackoverflow.com/questions/45204267/aframe-cycle-through-colors-using-array

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