2017-07-20 44 views
0

我一直在嘗試使用自定義組件循環顏色。Aframe:通過顏色循環使用數組

<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> 

該組件使用status來設置click事件的顏色屬性,但這看起來效率不高。這可以使用數組而不是狀態來實現嗎?

演示 - https://codepen.io/MannyMeadows/pen/GWzJRB

回答

1

你可以讓一個數組['red','green','blue']和循環通過它:

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

似乎數組更好的是,現在的動態,不知道怎麼樣的表現。 在這裏工作的小提琴:https://jsfiddle.net/gftruj/g9wfLgab/2/