canvashtml5-canvasadobe-animate

Loop function to play random movieclip


I'm using Adobe Animate to create a simple HTML5 Canvas animation that has stars animating randomly in the background. I have 10 stars named star1 - star10 as I want to only have 10 of them playing in specific places. I've been trying to create a function that will loop, pick a random number from 1-10 then play that movieclip.

This is my current code:

setInterval(function(){
    var myNum = Math.round(Math.random() * 10) + 1;
    thisMc = this["star" + myNum];
    thisMc.play();
}, 800);

The function is looping and is picking a random number between 1-10, but I just can't get it to play the movieclip. When I use this["star" + myNum]; it comes back as unidentified, but if I use ["star" + myNum]; then it comes back as ["star1"]. I'm not sure how to get the code to compile the actual movieclip name and to play it.


Solution

  • You have to save the context to another object outside the setInterval() function, and use that inside the function.

    let ctx = this;
    setInterval(function(){
        var myNum = Math.round(Math.random() * 10) + 1;
        thisMc = ctx["star" + myNum];
        thisMc.play();
    }, 800);
    

    This should work.