1

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.

mortalbug
  • 13
  • 3
  • Why are you using the `this` keyword? – lloydaf Nov 29 '18 at 11:49
  • Also, can you share some code? – lloydaf Nov 29 '18 at 11:53
  • I thought that I needed to use 'this' for it to compile the movieclip name. In ActionScript I could use eval to compile the movieclip name. I've searched around a lot here and on Google and thought that using ["star" + myNum]; would work the same as eval used to. As far as code goes, this is all of it other than the 10 movieclips on the canvas which are named star1 - star10. – mortalbug Nov 29 '18 at 11:57
  • If you `console.log(this)`, it will probably point to the anonymous function context. How are you having the movie clips in the canvas? Do they have an id attribute? – lloydaf Nov 29 '18 at 12:03
  • I did console.log(thisMc); which came back with unidentified when I had thisMc = this["star" + myNum]; the console came back with ["star1"] or whatever random number it'd picked. Yes, the movieclips all have id attributes and I can get them to play if I just use this.star1.play(); (or whatever number) outside of the function. – mortalbug Nov 29 '18 at 12:11
  • When I try to use console.log(this); I just get a list of hundreds of variables in the console window. – mortalbug Nov 29 '18 at 12:14
  • Ok understood what you are saying. Try the window object. `thisMc = window["star"+myNum];` then, you can try `thisMc.play()`. Does that work? – lloydaf Nov 29 '18 at 12:19
  • In the console it still comes back with unidentified' when I have console.log(thisMc); – mortalbug Nov 29 '18 at 12:27
  • Check my answer below, should do it for you. – lloydaf Nov 29 '18 at 12:33

1 Answers1

0

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.

lloydaf
  • 605
  • 3
  • 17